babylon.max.js 4.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * 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.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1110. */
  1111. Color3.prototype.add = function (otherColor) {
  1112. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1113. };
  1114. /**
  1115. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1116. * Returns the unmodified current Color3.
  1117. */
  1118. Color3.prototype.addToRef = function (otherColor, result) {
  1119. result.r = this.r + otherColor.r;
  1120. result.g = this.g + otherColor.g;
  1121. result.b = this.b + otherColor.b;
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1126. */
  1127. Color3.prototype.subtract = function (otherColor) {
  1128. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.subtractToRef = function (otherColor, result) {
  1135. result.r = this.r - otherColor.r;
  1136. result.g = this.g - otherColor.g;
  1137. result.b = this.b - otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 copied the current one.
  1142. */
  1143. Color3.prototype.clone = function () {
  1144. return new Color3(this.r, this.g, this.b);
  1145. };
  1146. /**
  1147. * Copies the rgb values from the source in the current Color3.
  1148. * Returns the updated Color3.
  1149. */
  1150. Color3.prototype.copyFrom = function (source) {
  1151. this.r = source.r;
  1152. this.g = source.g;
  1153. this.b = source.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Updates the Color3 rgb values from the passed floats.
  1158. * Returns the Color3.
  1159. */
  1160. Color3.prototype.copyFromFloats = function (r, g, b) {
  1161. this.r = r;
  1162. this.g = g;
  1163. this.b = b;
  1164. return this;
  1165. };
  1166. /**
  1167. * Updates the Color3 rgb values from the passed floats.
  1168. * Returns the Color3.
  1169. */
  1170. Color3.prototype.set = function (r, g, b) {
  1171. return this.copyFromFloats(r, g, b);
  1172. };
  1173. /**
  1174. * Returns the Color3 hexadecimal code as a string.
  1175. */
  1176. Color3.prototype.toHexString = function () {
  1177. var intR = (this.r * 255) | 0;
  1178. var intG = (this.g * 255) | 0;
  1179. var intB = (this.b * 255) | 0;
  1180. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1181. };
  1182. /**
  1183. * Returns a new Color3 converted to linear space.
  1184. */
  1185. Color3.prototype.toLinearSpace = function () {
  1186. var convertedColor = new Color3();
  1187. this.toLinearSpaceToRef(convertedColor);
  1188. return convertedColor;
  1189. };
  1190. /**
  1191. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1192. * Returns the unmodified Color3.
  1193. */
  1194. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1195. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1196. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1197. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Color3 converted to gamma space.
  1202. */
  1203. Color3.prototype.toGammaSpace = function () {
  1204. var convertedColor = new Color3();
  1205. this.toGammaSpaceToRef(convertedColor);
  1206. return convertedColor;
  1207. };
  1208. /**
  1209. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1210. * Returns the unmodified Color3.
  1211. */
  1212. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1213. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1214. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1215. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1216. return this;
  1217. };
  1218. // Statics
  1219. /**
  1220. * Creates a new Color3 from the string containing valid hexadecimal values.
  1221. */
  1222. Color3.FromHexString = function (hex) {
  1223. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1224. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1225. return new Color3(0, 0, 0);
  1226. }
  1227. var r = parseInt(hex.substring(1, 3), 16);
  1228. var g = parseInt(hex.substring(3, 5), 16);
  1229. var b = parseInt(hex.substring(5, 7), 16);
  1230. return Color3.FromInts(r, g, b);
  1231. };
  1232. /**
  1233. * Creates a new Vector3 from the startind index of the passed array.
  1234. */
  1235. Color3.FromArray = function (array, offset) {
  1236. if (offset === void 0) { offset = 0; }
  1237. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1238. };
  1239. /**
  1240. * Creates a new Color3 from integer values ( < 256).
  1241. */
  1242. Color3.FromInts = function (r, g, b) {
  1243. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1244. };
  1245. /**
  1246. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1247. */
  1248. Color3.Lerp = function (start, end, amount) {
  1249. var r = start.r + ((end.r - start.r) * amount);
  1250. var g = start.g + ((end.g - start.g) * amount);
  1251. var b = start.b + ((end.b - start.b) * amount);
  1252. return new Color3(r, g, b);
  1253. };
  1254. Color3.Red = function () { return new Color3(1, 0, 0); };
  1255. Color3.Green = function () { return new Color3(0, 1, 0); };
  1256. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1257. Color3.Black = function () { return new Color3(0, 0, 0); };
  1258. Color3.White = function () { return new Color3(1, 1, 1); };
  1259. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1260. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1261. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1262. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1263. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1264. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1265. return Color3;
  1266. }());
  1267. BABYLON.Color3 = Color3;
  1268. var Color4 = /** @class */ (function () {
  1269. /**
  1270. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1271. */
  1272. function Color4(r, g, b, a) {
  1273. if (r === void 0) { r = 0; }
  1274. if (g === void 0) { g = 0; }
  1275. if (b === void 0) { b = 0; }
  1276. if (a === void 0) { a = 1; }
  1277. this.r = r;
  1278. this.g = g;
  1279. this.b = b;
  1280. this.a = a;
  1281. }
  1282. // Operators
  1283. /**
  1284. * Adds in place the passed Color4 values to the current Color4.
  1285. * Returns the updated Color4.
  1286. */
  1287. Color4.prototype.addInPlace = function (right) {
  1288. this.r += right.r;
  1289. this.g += right.g;
  1290. this.b += right.b;
  1291. this.a += right.a;
  1292. return this;
  1293. };
  1294. /**
  1295. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1296. */
  1297. Color4.prototype.asArray = function () {
  1298. var result = new Array();
  1299. this.toArray(result, 0);
  1300. return result;
  1301. };
  1302. /**
  1303. * Stores from the starting index in the passed array the Color4 successive values.
  1304. * Returns the Color4.
  1305. */
  1306. Color4.prototype.toArray = function (array, index) {
  1307. if (index === undefined) {
  1308. index = 0;
  1309. }
  1310. array[index] = this.r;
  1311. array[index + 1] = this.g;
  1312. array[index + 2] = this.b;
  1313. array[index + 3] = this.a;
  1314. return this;
  1315. };
  1316. /**
  1317. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1318. */
  1319. Color4.prototype.add = function (right) {
  1320. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1321. };
  1322. /**
  1323. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1324. */
  1325. Color4.prototype.subtract = function (right) {
  1326. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1327. };
  1328. /**
  1329. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1330. * Returns the Color4.
  1331. */
  1332. Color4.prototype.subtractToRef = function (right, result) {
  1333. result.r = this.r - right.r;
  1334. result.g = this.g - right.g;
  1335. result.b = this.b - right.b;
  1336. result.a = this.a - right.a;
  1337. return this;
  1338. };
  1339. /**
  1340. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1341. */
  1342. Color4.prototype.scale = function (scale) {
  1343. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1344. };
  1345. /**
  1346. * Multiplies the current Color4 values by scale and stores the result in "result".
  1347. * Returns the Color4.
  1348. */
  1349. Color4.prototype.scaleToRef = function (scale, result) {
  1350. result.r = this.r * scale;
  1351. result.g = this.g * scale;
  1352. result.b = this.b * scale;
  1353. result.a = this.a * scale;
  1354. return this;
  1355. };
  1356. /**
  1357. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1358. * @param color The Color4 (RGBA) value to multiply by
  1359. * @returns A new Color4.
  1360. */
  1361. Color4.prototype.multiply = function (color) {
  1362. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1363. };
  1364. /**
  1365. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1366. * @param color The Color4 (RGBA) value to multiply by
  1367. * @param result The Color4 (RGBA) to fill the result in
  1368. * @returns the result Color4.
  1369. */
  1370. Color4.prototype.multiplyToRef = function (color, result) {
  1371. result.r = this.r * color.r;
  1372. result.g = this.g * color.g;
  1373. result.b = this.b * color.b;
  1374. result.a = this.a * color.a;
  1375. return result;
  1376. };
  1377. /**
  1378. * Returns a string with the Color4 values.
  1379. */
  1380. Color4.prototype.toString = function () {
  1381. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1382. };
  1383. /**
  1384. * Returns the string "Color4"
  1385. */
  1386. Color4.prototype.getClassName = function () {
  1387. return "Color4";
  1388. };
  1389. /**
  1390. * Return the Color4 hash code as a number.
  1391. */
  1392. Color4.prototype.getHashCode = function () {
  1393. var hash = this.r || 0;
  1394. hash = (hash * 397) ^ (this.g || 0);
  1395. hash = (hash * 397) ^ (this.b || 0);
  1396. hash = (hash * 397) ^ (this.a || 0);
  1397. return hash;
  1398. };
  1399. /**
  1400. * Creates a new Color4 copied from the current one.
  1401. */
  1402. Color4.prototype.clone = function () {
  1403. return new Color4(this.r, this.g, this.b, this.a);
  1404. };
  1405. /**
  1406. * Copies the passed Color4 values into the current one.
  1407. * Returns the updated Color4.
  1408. */
  1409. Color4.prototype.copyFrom = function (source) {
  1410. this.r = source.r;
  1411. this.g = source.g;
  1412. this.b = source.b;
  1413. this.a = source.a;
  1414. return this;
  1415. };
  1416. /**
  1417. * Copies the passed float values into the current one.
  1418. * Returns the updated Color4.
  1419. */
  1420. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1421. this.r = r;
  1422. this.g = g;
  1423. this.b = b;
  1424. this.a = a;
  1425. return this;
  1426. };
  1427. /**
  1428. * Copies the passed float values into the current one.
  1429. * Returns the updated Color4.
  1430. */
  1431. Color4.prototype.set = function (r, g, b, a) {
  1432. return this.copyFromFloats(r, g, b, a);
  1433. };
  1434. /**
  1435. * Returns a string containing the hexadecimal Color4 code.
  1436. */
  1437. Color4.prototype.toHexString = function () {
  1438. var intR = (this.r * 255) | 0;
  1439. var intG = (this.g * 255) | 0;
  1440. var intB = (this.b * 255) | 0;
  1441. var intA = (this.a * 255) | 0;
  1442. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1443. };
  1444. /**
  1445. * Returns a new Color4 converted to linear space.
  1446. */
  1447. Color4.prototype.toLinearSpace = function () {
  1448. var convertedColor = new Color4();
  1449. this.toLinearSpaceToRef(convertedColor);
  1450. return convertedColor;
  1451. };
  1452. /**
  1453. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1454. * Returns the unmodified Color4.
  1455. */
  1456. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1457. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1458. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1459. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1460. convertedColor.a = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new Color4 converted to gamma space.
  1465. */
  1466. Color4.prototype.toGammaSpace = function () {
  1467. var convertedColor = new Color4();
  1468. this.toGammaSpaceToRef(convertedColor);
  1469. return convertedColor;
  1470. };
  1471. /**
  1472. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1473. * Returns the unmodified Color4.
  1474. */
  1475. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1476. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1477. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1478. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1479. convertedColor.a = this.a;
  1480. return this;
  1481. };
  1482. // Statics
  1483. /**
  1484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1485. */
  1486. Color4.FromHexString = function (hex) {
  1487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1489. return new Color4(0.0, 0.0, 0.0, 0.0);
  1490. }
  1491. var r = parseInt(hex.substring(1, 3), 16);
  1492. var g = parseInt(hex.substring(3, 5), 16);
  1493. var b = parseInt(hex.substring(5, 7), 16);
  1494. var a = parseInt(hex.substring(7, 9), 16);
  1495. return Color4.FromInts(r, g, b, a);
  1496. };
  1497. /**
  1498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1499. */
  1500. Color4.Lerp = function (left, right, amount) {
  1501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1502. Color4.LerpToRef(left, right, amount, result);
  1503. return result;
  1504. };
  1505. /**
  1506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1507. */
  1508. Color4.LerpToRef = function (left, right, amount, result) {
  1509. result.r = left.r + (right.r - left.r) * amount;
  1510. result.g = left.g + (right.g - left.g) * amount;
  1511. result.b = left.b + (right.b - left.b) * amount;
  1512. result.a = left.a + (right.a - left.a) * amount;
  1513. };
  1514. /**
  1515. * Creates a new Color4 from the starting index element of the passed array.
  1516. */
  1517. Color4.FromArray = function (array, offset) {
  1518. if (offset === void 0) { offset = 0; }
  1519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1520. };
  1521. /**
  1522. * Creates a new Color4 from the passed integers ( < 256 ).
  1523. */
  1524. Color4.FromInts = function (r, g, b, a) {
  1525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1526. };
  1527. Color4.CheckColors4 = function (colors, count) {
  1528. // Check if color3 was used
  1529. if (colors.length === count * 3) {
  1530. var colors4 = [];
  1531. for (var index = 0; index < colors.length; index += 3) {
  1532. var newIndex = (index / 3) * 4;
  1533. colors4[newIndex] = colors[index];
  1534. colors4[newIndex + 1] = colors[index + 1];
  1535. colors4[newIndex + 2] = colors[index + 2];
  1536. colors4[newIndex + 3] = 1.0;
  1537. }
  1538. return colors4;
  1539. }
  1540. return colors;
  1541. };
  1542. return Color4;
  1543. }());
  1544. BABYLON.Color4 = Color4;
  1545. var Vector2 = /** @class */ (function () {
  1546. /**
  1547. * Creates a new Vector2 from the passed x and y coordinates.
  1548. */
  1549. function Vector2(x, y) {
  1550. this.x = x;
  1551. this.y = y;
  1552. }
  1553. /**
  1554. * Returns a string with the Vector2 coordinates.
  1555. */
  1556. Vector2.prototype.toString = function () {
  1557. return "{X: " + this.x + " Y:" + this.y + "}";
  1558. };
  1559. /**
  1560. * Returns the string "Vector2"
  1561. */
  1562. Vector2.prototype.getClassName = function () {
  1563. return "Vector2";
  1564. };
  1565. /**
  1566. * Returns the Vector2 hash code as a number.
  1567. */
  1568. Vector2.prototype.getHashCode = function () {
  1569. var hash = this.x || 0;
  1570. hash = (hash * 397) ^ (this.y || 0);
  1571. return hash;
  1572. };
  1573. // Operators
  1574. /**
  1575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1576. * Returns the Vector2.
  1577. */
  1578. Vector2.prototype.toArray = function (array, index) {
  1579. if (index === void 0) { index = 0; }
  1580. array[index] = this.x;
  1581. array[index + 1] = this.y;
  1582. return this;
  1583. };
  1584. /**
  1585. * Returns a new array with 2 elements : the Vector2 coordinates.
  1586. */
  1587. Vector2.prototype.asArray = function () {
  1588. var result = new Array();
  1589. this.toArray(result, 0);
  1590. return result;
  1591. };
  1592. /**
  1593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1594. * Returns the updated Vector2.
  1595. */
  1596. Vector2.prototype.copyFrom = function (source) {
  1597. this.x = source.x;
  1598. this.y = source.y;
  1599. return this;
  1600. };
  1601. /**
  1602. * Sets the Vector2 coordinates with the passed floats.
  1603. * Returns the updated Vector2.
  1604. */
  1605. Vector2.prototype.copyFromFloats = function (x, y) {
  1606. this.x = x;
  1607. this.y = y;
  1608. return this;
  1609. };
  1610. /**
  1611. * Sets the Vector2 coordinates with the passed floats.
  1612. * Returns the updated Vector2.
  1613. */
  1614. Vector2.prototype.set = function (x, y) {
  1615. return this.copyFromFloats(x, y);
  1616. };
  1617. /**
  1618. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1619. */
  1620. Vector2.prototype.add = function (otherVector) {
  1621. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1622. };
  1623. /**
  1624. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1625. * Returns the Vector2.
  1626. */
  1627. Vector2.prototype.addToRef = function (otherVector, result) {
  1628. result.x = this.x + otherVector.x;
  1629. result.y = this.y + otherVector.y;
  1630. return this;
  1631. };
  1632. /**
  1633. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1634. * Returns the updated Vector2.
  1635. */
  1636. Vector2.prototype.addInPlace = function (otherVector) {
  1637. this.x += otherVector.x;
  1638. this.y += otherVector.y;
  1639. return this;
  1640. };
  1641. /**
  1642. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1643. */
  1644. Vector2.prototype.addVector3 = function (otherVector) {
  1645. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1646. };
  1647. /**
  1648. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1649. */
  1650. Vector2.prototype.subtract = function (otherVector) {
  1651. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1652. };
  1653. /**
  1654. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1655. * Returns the Vector2.
  1656. */
  1657. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1658. result.x = this.x - otherVector.x;
  1659. result.y = this.y - otherVector.y;
  1660. return this;
  1661. };
  1662. /**
  1663. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1664. * Returns the updated Vector2.
  1665. */
  1666. Vector2.prototype.subtractInPlace = function (otherVector) {
  1667. this.x -= otherVector.x;
  1668. this.y -= otherVector.y;
  1669. return this;
  1670. };
  1671. /**
  1672. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1673. * Returns the updated Vector2.
  1674. */
  1675. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1676. this.x *= otherVector.x;
  1677. this.y *= otherVector.y;
  1678. return this;
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1682. */
  1683. Vector2.prototype.multiply = function (otherVector) {
  1684. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1685. };
  1686. /**
  1687. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1691. result.x = this.x * otherVector.x;
  1692. result.y = this.y * otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1697. */
  1698. Vector2.prototype.multiplyByFloats = function (x, y) {
  1699. return new Vector2(this.x * x, this.y * y);
  1700. };
  1701. /**
  1702. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1703. */
  1704. Vector2.prototype.divide = function (otherVector) {
  1705. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1706. };
  1707. /**
  1708. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1709. * Returns the Vector2.
  1710. */
  1711. Vector2.prototype.divideToRef = function (otherVector, result) {
  1712. result.x = this.x / otherVector.x;
  1713. result.y = this.y / otherVector.y;
  1714. return this;
  1715. };
  1716. /**
  1717. * Divides the current Vector3 coordinates by the passed ones.
  1718. * Returns the updated Vector3.
  1719. */
  1720. Vector2.prototype.divideInPlace = function (otherVector) {
  1721. return this.divideToRef(otherVector, this);
  1722. };
  1723. /**
  1724. * Returns a new Vector2 with current Vector2 negated coordinates.
  1725. */
  1726. Vector2.prototype.negate = function () {
  1727. return new Vector2(-this.x, -this.y);
  1728. };
  1729. /**
  1730. * Multiply the Vector2 coordinates by scale.
  1731. * Returns the updated Vector2.
  1732. */
  1733. Vector2.prototype.scaleInPlace = function (scale) {
  1734. this.x *= scale;
  1735. this.y *= scale;
  1736. return this;
  1737. };
  1738. /**
  1739. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1740. */
  1741. Vector2.prototype.scale = function (scale) {
  1742. return new Vector2(this.x * scale, this.y * scale);
  1743. };
  1744. /**
  1745. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1746. */
  1747. Vector2.prototype.equals = function (otherVector) {
  1748. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1749. };
  1750. /**
  1751. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1752. */
  1753. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1754. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1755. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1756. };
  1757. // Properties
  1758. /**
  1759. * Returns the vector length (float).
  1760. */
  1761. Vector2.prototype.length = function () {
  1762. return Math.sqrt(this.x * this.x + this.y * this.y);
  1763. };
  1764. /**
  1765. * Returns the vector squared length (float);
  1766. */
  1767. Vector2.prototype.lengthSquared = function () {
  1768. return (this.x * this.x + this.y * this.y);
  1769. };
  1770. // Methods
  1771. /**
  1772. * Normalize the vector.
  1773. * Returns the updated Vector2.
  1774. */
  1775. Vector2.prototype.normalize = function () {
  1776. var len = this.length();
  1777. if (len === 0)
  1778. return this;
  1779. var num = 1.0 / len;
  1780. this.x *= num;
  1781. this.y *= num;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector2 copied from the Vector2.
  1786. */
  1787. Vector2.prototype.clone = function () {
  1788. return new Vector2(this.x, this.y);
  1789. };
  1790. // Statics
  1791. /**
  1792. * Returns a new Vector2(0, 0)
  1793. */
  1794. Vector2.Zero = function () {
  1795. return new Vector2(0, 0);
  1796. };
  1797. /**
  1798. * Returns a new Vector2(1, 1)
  1799. */
  1800. Vector2.One = function () {
  1801. return new Vector2(1, 1);
  1802. };
  1803. /**
  1804. * Returns a new Vector2 set from the passed index element of the passed array.
  1805. */
  1806. Vector2.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Vector2(array[offset], array[offset + 1]);
  1809. };
  1810. /**
  1811. * Sets "result" from the passed index element of the passed array.
  1812. */
  1813. Vector2.FromArrayToRef = function (array, offset, result) {
  1814. result.x = array[offset];
  1815. result.y = array[offset + 1];
  1816. };
  1817. /**
  1818. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1819. */
  1820. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1821. var squared = amount * amount;
  1822. var cubed = amount * squared;
  1823. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1824. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1825. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1826. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1827. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1828. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1829. return new Vector2(x, y);
  1830. };
  1831. /**
  1832. * 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".
  1833. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1834. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1835. */
  1836. Vector2.Clamp = function (value, min, max) {
  1837. var x = value.x;
  1838. x = (x > max.x) ? max.x : x;
  1839. x = (x < min.x) ? min.x : x;
  1840. var y = value.y;
  1841. y = (y > max.y) ? max.y : y;
  1842. y = (y < min.y) ? min.y : y;
  1843. return new Vector2(x, y);
  1844. };
  1845. /**
  1846. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1847. */
  1848. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1849. var squared = amount * amount;
  1850. var cubed = amount * squared;
  1851. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1852. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1853. var part3 = (cubed - (2.0 * squared)) + amount;
  1854. var part4 = cubed - squared;
  1855. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1856. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1857. return new Vector2(x, y);
  1858. };
  1859. /**
  1860. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1861. */
  1862. Vector2.Lerp = function (start, end, amount) {
  1863. var x = start.x + ((end.x - start.x) * amount);
  1864. var y = start.y + ((end.y - start.y) * amount);
  1865. return new Vector2(x, y);
  1866. };
  1867. /**
  1868. * Returns the dot product (float) of the vector "left" and the vector "right".
  1869. */
  1870. Vector2.Dot = function (left, right) {
  1871. return left.x * right.x + left.y * right.y;
  1872. };
  1873. /**
  1874. * Returns a new Vector2 equal to the normalized passed vector.
  1875. */
  1876. Vector2.Normalize = function (vector) {
  1877. var newVector = vector.clone();
  1878. newVector.normalize();
  1879. return newVector;
  1880. };
  1881. /**
  1882. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1883. */
  1884. Vector2.Minimize = function (left, right) {
  1885. var x = (left.x < right.x) ? left.x : right.x;
  1886. var y = (left.y < right.y) ? left.y : right.y;
  1887. return new Vector2(x, y);
  1888. };
  1889. /**
  1890. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1891. */
  1892. Vector2.Maximize = function (left, right) {
  1893. var x = (left.x > right.x) ? left.x : right.x;
  1894. var y = (left.y > right.y) ? left.y : right.y;
  1895. return new Vector2(x, y);
  1896. };
  1897. /**
  1898. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1899. */
  1900. Vector2.Transform = function (vector, transformation) {
  1901. var r = Vector2.Zero();
  1902. Vector2.TransformToRef(vector, transformation, r);
  1903. return r;
  1904. };
  1905. /**
  1906. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1907. */
  1908. Vector2.TransformToRef = function (vector, transformation, result) {
  1909. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1910. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1911. result.x = x;
  1912. result.y = y;
  1913. };
  1914. /**
  1915. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1916. */
  1917. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1918. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1919. var sign = a < 0 ? -1 : 1;
  1920. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1921. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1922. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1923. };
  1924. /**
  1925. * Returns the distance (float) between the vectors "value1" and "value2".
  1926. */
  1927. Vector2.Distance = function (value1, value2) {
  1928. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1929. };
  1930. /**
  1931. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1932. */
  1933. Vector2.DistanceSquared = function (value1, value2) {
  1934. var x = value1.x - value2.x;
  1935. var y = value1.y - value2.y;
  1936. return (x * x) + (y * y);
  1937. };
  1938. /**
  1939. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1940. */
  1941. Vector2.Center = function (value1, value2) {
  1942. var center = value1.add(value2);
  1943. center.scaleInPlace(0.5);
  1944. return center;
  1945. };
  1946. /**
  1947. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1948. */
  1949. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1950. var l2 = Vector2.DistanceSquared(segA, segB);
  1951. if (l2 === 0.0) {
  1952. return Vector2.Distance(p, segA);
  1953. }
  1954. var v = segB.subtract(segA);
  1955. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1956. var proj = segA.add(v.multiplyByFloats(t, t));
  1957. return Vector2.Distance(p, proj);
  1958. };
  1959. return Vector2;
  1960. }());
  1961. BABYLON.Vector2 = Vector2;
  1962. var Vector3 = /** @class */ (function () {
  1963. /**
  1964. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1965. * A Vector3 is the main object used in 3D geometry.
  1966. * It can represent etiher the coordinates of a point the space, either a direction.
  1967. */
  1968. function Vector3(x, y, z) {
  1969. this.x = x;
  1970. this.y = y;
  1971. this.z = z;
  1972. }
  1973. /**
  1974. * Returns a string with the Vector3 coordinates.
  1975. */
  1976. Vector3.prototype.toString = function () {
  1977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1978. };
  1979. /**
  1980. * Returns the string "Vector3"
  1981. */
  1982. Vector3.prototype.getClassName = function () {
  1983. return "Vector3";
  1984. };
  1985. /**
  1986. * Returns the Vector hash code.
  1987. */
  1988. Vector3.prototype.getHashCode = function () {
  1989. var hash = this.x || 0;
  1990. hash = (hash * 397) ^ (this.y || 0);
  1991. hash = (hash * 397) ^ (this.z || 0);
  1992. return hash;
  1993. };
  1994. // Operators
  1995. /**
  1996. * Returns a new array with three elements : the coordinates the Vector3.
  1997. */
  1998. Vector3.prototype.asArray = function () {
  1999. var result = [];
  2000. this.toArray(result, 0);
  2001. return result;
  2002. };
  2003. /**
  2004. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2005. * Returns the Vector3.
  2006. */
  2007. Vector3.prototype.toArray = function (array, index) {
  2008. if (index === void 0) { index = 0; }
  2009. array[index] = this.x;
  2010. array[index + 1] = this.y;
  2011. array[index + 2] = this.z;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2016. */
  2017. Vector3.prototype.toQuaternion = function () {
  2018. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2019. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2020. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2021. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2022. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2023. var cosy = Math.cos(this.y * 0.5);
  2024. var siny = Math.sin(this.y * 0.5);
  2025. result.x = coszMinusx * siny;
  2026. result.y = -sinzMinusx * siny;
  2027. result.z = sinxPlusz * cosy;
  2028. result.w = cosxPlusz * cosy;
  2029. return result;
  2030. };
  2031. /**
  2032. * Adds the passed vector to the current Vector3.
  2033. * Returns the updated Vector3.
  2034. */
  2035. Vector3.prototype.addInPlace = function (otherVector) {
  2036. this.x += otherVector.x;
  2037. this.y += otherVector.y;
  2038. this.z += otherVector.z;
  2039. return this;
  2040. };
  2041. /**
  2042. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2043. */
  2044. Vector3.prototype.add = function (otherVector) {
  2045. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2046. };
  2047. /**
  2048. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2049. * Returns the current Vector3.
  2050. */
  2051. Vector3.prototype.addToRef = function (otherVector, result) {
  2052. result.x = this.x + otherVector.x;
  2053. result.y = this.y + otherVector.y;
  2054. result.z = this.z + otherVector.z;
  2055. return this;
  2056. };
  2057. /**
  2058. * Subtract the passed vector from the current Vector3.
  2059. * Returns the updated Vector3.
  2060. */
  2061. Vector3.prototype.subtractInPlace = function (otherVector) {
  2062. this.x -= otherVector.x;
  2063. this.y -= otherVector.y;
  2064. this.z -= otherVector.z;
  2065. return this;
  2066. };
  2067. /**
  2068. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2069. */
  2070. Vector3.prototype.subtract = function (otherVector) {
  2071. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2072. };
  2073. /**
  2074. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2075. * Returns the current Vector3.
  2076. */
  2077. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2078. result.x = this.x - otherVector.x;
  2079. result.y = this.y - otherVector.y;
  2080. result.z = this.z - otherVector.z;
  2081. return this;
  2082. };
  2083. /**
  2084. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2085. */
  2086. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2087. return new Vector3(this.x - x, this.y - y, this.z - z);
  2088. };
  2089. /**
  2090. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2091. * Returns the current Vector3.
  2092. */
  2093. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2094. result.x = this.x - x;
  2095. result.y = this.y - y;
  2096. result.z = this.z - z;
  2097. return this;
  2098. };
  2099. /**
  2100. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2101. */
  2102. Vector3.prototype.negate = function () {
  2103. return new Vector3(-this.x, -this.y, -this.z);
  2104. };
  2105. /**
  2106. * Multiplies the Vector3 coordinates by the float "scale".
  2107. * Returns the updated Vector3.
  2108. */
  2109. Vector3.prototype.scaleInPlace = function (scale) {
  2110. this.x *= scale;
  2111. this.y *= scale;
  2112. this.z *= scale;
  2113. return this;
  2114. };
  2115. /**
  2116. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2117. */
  2118. Vector3.prototype.scale = function (scale) {
  2119. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2120. };
  2121. /**
  2122. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2123. * Returns the current Vector3.
  2124. */
  2125. Vector3.prototype.scaleToRef = function (scale, result) {
  2126. result.x = this.x * scale;
  2127. result.y = this.y * scale;
  2128. result.z = this.z * scale;
  2129. return this;
  2130. };
  2131. /**
  2132. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2133. */
  2134. Vector3.prototype.equals = function (otherVector) {
  2135. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2136. };
  2137. /**
  2138. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2139. */
  2140. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2141. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2142. 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);
  2143. };
  2144. /**
  2145. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2146. */
  2147. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2148. return this.x === x && this.y === y && this.z === z;
  2149. };
  2150. /**
  2151. * Muliplies the current Vector3 coordinates by the passed ones.
  2152. * Returns the updated Vector3.
  2153. */
  2154. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2155. this.x *= otherVector.x;
  2156. this.y *= otherVector.y;
  2157. this.z *= otherVector.z;
  2158. return this;
  2159. };
  2160. /**
  2161. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2162. */
  2163. Vector3.prototype.multiply = function (otherVector) {
  2164. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2165. };
  2166. /**
  2167. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2168. * Returns the current Vector3.
  2169. */
  2170. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2171. result.x = this.x * otherVector.x;
  2172. result.y = this.y * otherVector.y;
  2173. result.z = this.z * otherVector.z;
  2174. return this;
  2175. };
  2176. /**
  2177. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2178. */
  2179. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2180. return new Vector3(this.x * x, this.y * y, this.z * z);
  2181. };
  2182. /**
  2183. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2184. */
  2185. Vector3.prototype.divide = function (otherVector) {
  2186. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2187. };
  2188. /**
  2189. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2190. * Returns the current Vector3.
  2191. */
  2192. Vector3.prototype.divideToRef = function (otherVector, result) {
  2193. result.x = this.x / otherVector.x;
  2194. result.y = this.y / otherVector.y;
  2195. result.z = this.z / otherVector.z;
  2196. return this;
  2197. };
  2198. /**
  2199. * Divides the current Vector3 coordinates by the passed ones.
  2200. * Returns the updated Vector3.
  2201. */
  2202. Vector3.prototype.divideInPlace = function (otherVector) {
  2203. return this.divideToRef(otherVector, this);
  2204. };
  2205. /**
  2206. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2207. * Returns the updated Vector3.
  2208. */
  2209. Vector3.prototype.MinimizeInPlace = function (other) {
  2210. if (other.x < this.x)
  2211. this.x = other.x;
  2212. if (other.y < this.y)
  2213. this.y = other.y;
  2214. if (other.z < this.z)
  2215. this.z = other.z;
  2216. return this;
  2217. };
  2218. /**
  2219. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2220. * Returns the updated Vector3.
  2221. */
  2222. Vector3.prototype.MaximizeInPlace = function (other) {
  2223. if (other.x > this.x)
  2224. this.x = other.x;
  2225. if (other.y > this.y)
  2226. this.y = other.y;
  2227. if (other.z > this.z)
  2228. this.z = other.z;
  2229. return this;
  2230. };
  2231. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2232. /**
  2233. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2234. */
  2235. get: function () {
  2236. var absX = Math.abs(this.x);
  2237. var absY = Math.abs(this.y);
  2238. if (absX !== absY) {
  2239. return true;
  2240. }
  2241. var absZ = Math.abs(this.z);
  2242. if (absX !== absZ) {
  2243. return true;
  2244. }
  2245. if (absY !== absZ) {
  2246. return true;
  2247. }
  2248. return false;
  2249. },
  2250. enumerable: true,
  2251. configurable: true
  2252. });
  2253. // Properties
  2254. /**
  2255. * Returns the length of the Vector3 (float).
  2256. */
  2257. Vector3.prototype.length = function () {
  2258. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2259. };
  2260. /**
  2261. * Returns the squared length of the Vector3 (float).
  2262. */
  2263. Vector3.prototype.lengthSquared = function () {
  2264. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2265. };
  2266. /**
  2267. * Normalize the current Vector3.
  2268. * Returns the updated Vector3.
  2269. * /!\ In place operation.
  2270. */
  2271. Vector3.prototype.normalize = function () {
  2272. var len = this.length();
  2273. if (len === 0 || len === 1.0)
  2274. return this;
  2275. var num = 1.0 / len;
  2276. this.x *= num;
  2277. this.y *= num;
  2278. this.z *= num;
  2279. return this;
  2280. };
  2281. /**
  2282. * Normalize the current Vector3 to a new vector.
  2283. * @returns the new Vector3.
  2284. */
  2285. Vector3.prototype.normalizeToNew = function () {
  2286. var normalized = new Vector3(0, 0, 0);
  2287. this.normalizeToRef(normalized);
  2288. return normalized;
  2289. };
  2290. /**
  2291. * Normalize the current Vector3 to the reference.
  2292. * @param the reference to update.
  2293. * @returns the updated Vector3.
  2294. */
  2295. Vector3.prototype.normalizeToRef = function (reference) {
  2296. var len = this.length();
  2297. if (len === 0 || len === 1.0) {
  2298. reference.set(this.x, this.y, this.z);
  2299. return reference;
  2300. }
  2301. var scale = 1.0 / len;
  2302. this.scaleToRef(scale, reference);
  2303. return reference;
  2304. };
  2305. /**
  2306. * Returns a new Vector3 copied from the current Vector3.
  2307. */
  2308. Vector3.prototype.clone = function () {
  2309. return new Vector3(this.x, this.y, this.z);
  2310. };
  2311. /**
  2312. * Copies the passed vector coordinates to the current Vector3 ones.
  2313. * Returns the updated Vector3.
  2314. */
  2315. Vector3.prototype.copyFrom = function (source) {
  2316. this.x = source.x;
  2317. this.y = source.y;
  2318. this.z = source.z;
  2319. return this;
  2320. };
  2321. /**
  2322. * Copies the passed floats to the current Vector3 coordinates.
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2326. this.x = x;
  2327. this.y = y;
  2328. this.z = z;
  2329. return this;
  2330. };
  2331. /**
  2332. * Copies the passed floats to the current Vector3 coordinates.
  2333. * Returns the updated Vector3.
  2334. */
  2335. Vector3.prototype.set = function (x, y, z) {
  2336. return this.copyFromFloats(x, y, z);
  2337. };
  2338. // Statics
  2339. /**
  2340. *
  2341. */
  2342. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2343. var d0 = Vector3.Dot(vector0, axis) - size;
  2344. var d1 = Vector3.Dot(vector1, axis) - size;
  2345. var s = d0 / (d0 - d1);
  2346. return s;
  2347. };
  2348. /**
  2349. * Returns a new Vector3 set from the index "offset" of the passed array.
  2350. */
  2351. Vector3.FromArray = function (array, offset) {
  2352. if (!offset) {
  2353. offset = 0;
  2354. }
  2355. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2356. };
  2357. /**
  2358. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2359. * This function is deprecated. Use FromArray instead.
  2360. */
  2361. Vector3.FromFloatArray = function (array, offset) {
  2362. return Vector3.FromArray(array, offset);
  2363. };
  2364. /**
  2365. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2366. */
  2367. Vector3.FromArrayToRef = function (array, offset, result) {
  2368. result.x = array[offset];
  2369. result.y = array[offset + 1];
  2370. result.z = array[offset + 2];
  2371. };
  2372. /**
  2373. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2374. * This function is deprecated. Use FromArrayToRef instead.
  2375. */
  2376. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2377. return Vector3.FromArrayToRef(array, offset, result);
  2378. };
  2379. /**
  2380. * Sets the passed vector "result" with the passed floats.
  2381. */
  2382. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2383. result.x = x;
  2384. result.y = y;
  2385. result.z = z;
  2386. };
  2387. /**
  2388. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2389. */
  2390. Vector3.Zero = function () {
  2391. return new Vector3(0.0, 0.0, 0.0);
  2392. };
  2393. /**
  2394. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2395. */
  2396. Vector3.One = function () {
  2397. return new Vector3(1.0, 1.0, 1.0);
  2398. };
  2399. /**
  2400. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2401. */
  2402. Vector3.Up = function () {
  2403. return new Vector3(0.0, 1.0, 0.0);
  2404. };
  2405. /**
  2406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2407. */
  2408. Vector3.Forward = function () {
  2409. return new Vector3(0.0, 0.0, 1.0);
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2413. */
  2414. Vector3.Right = function () {
  2415. return new Vector3(1.0, 0.0, 0.0);
  2416. };
  2417. /**
  2418. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2419. */
  2420. Vector3.Left = function () {
  2421. return new Vector3(-1.0, 0.0, 0.0);
  2422. };
  2423. /**
  2424. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2425. * This method computes tranformed coordinates only, not transformed direction vectors.
  2426. */
  2427. Vector3.TransformCoordinates = function (vector, transformation) {
  2428. var result = Vector3.Zero();
  2429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2430. return result;
  2431. };
  2432. /**
  2433. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2434. * This method computes tranformed coordinates only, not transformed direction vectors.
  2435. */
  2436. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2437. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2438. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2439. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2440. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2441. result.x = x / w;
  2442. result.y = y / w;
  2443. result.z = z / w;
  2444. };
  2445. /**
  2446. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2447. * This method computes tranformed coordinates only, not transformed direction vectors.
  2448. */
  2449. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2450. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2451. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2452. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2453. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2454. result.x = rx / rw;
  2455. result.y = ry / rw;
  2456. result.z = rz / rw;
  2457. };
  2458. /**
  2459. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2460. * This methods computes transformed normalized direction vectors only.
  2461. */
  2462. Vector3.TransformNormal = function (vector, transformation) {
  2463. var result = Vector3.Zero();
  2464. Vector3.TransformNormalToRef(vector, transformation, result);
  2465. return result;
  2466. };
  2467. /**
  2468. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2469. * This methods computes transformed normalized direction vectors only.
  2470. */
  2471. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2472. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2473. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2474. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2475. result.x = x;
  2476. result.y = y;
  2477. result.z = z;
  2478. };
  2479. /**
  2480. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2481. * This methods computes transformed normalized direction vectors only.
  2482. */
  2483. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2484. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2485. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2486. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2487. };
  2488. /**
  2489. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2490. */
  2491. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2492. var squared = amount * amount;
  2493. var cubed = amount * squared;
  2494. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2495. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2496. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2497. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2498. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2499. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2500. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2501. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2502. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2503. return new Vector3(x, y, z);
  2504. };
  2505. /**
  2506. * 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".
  2507. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2508. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2509. */
  2510. Vector3.Clamp = function (value, min, max) {
  2511. var x = value.x;
  2512. x = (x > max.x) ? max.x : x;
  2513. x = (x < min.x) ? min.x : x;
  2514. var y = value.y;
  2515. y = (y > max.y) ? max.y : y;
  2516. y = (y < min.y) ? min.y : y;
  2517. var z = value.z;
  2518. z = (z > max.z) ? max.z : z;
  2519. z = (z < min.z) ? min.z : z;
  2520. return new Vector3(x, y, z);
  2521. };
  2522. /**
  2523. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2524. */
  2525. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2526. var squared = amount * amount;
  2527. var cubed = amount * squared;
  2528. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2529. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2530. var part3 = (cubed - (2.0 * squared)) + amount;
  2531. var part4 = cubed - squared;
  2532. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2533. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2534. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2535. return new Vector3(x, y, z);
  2536. };
  2537. /**
  2538. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2539. */
  2540. Vector3.Lerp = function (start, end, amount) {
  2541. var result = new Vector3(0, 0, 0);
  2542. Vector3.LerpToRef(start, end, amount, result);
  2543. return result;
  2544. };
  2545. /**
  2546. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2547. */
  2548. Vector3.LerpToRef = function (start, end, amount, result) {
  2549. result.x = start.x + ((end.x - start.x) * amount);
  2550. result.y = start.y + ((end.y - start.y) * amount);
  2551. result.z = start.z + ((end.z - start.z) * amount);
  2552. };
  2553. /**
  2554. * Returns the dot product (float) between the vectors "left" and "right".
  2555. */
  2556. Vector3.Dot = function (left, right) {
  2557. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2558. };
  2559. /**
  2560. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2561. * The cross product is then orthogonal to both "left" and "right".
  2562. */
  2563. Vector3.Cross = function (left, right) {
  2564. var result = Vector3.Zero();
  2565. Vector3.CrossToRef(left, right, result);
  2566. return result;
  2567. };
  2568. /**
  2569. * Sets the passed vector "result" with the cross product of "left" and "right".
  2570. * The cross product is then orthogonal to both "left" and "right".
  2571. */
  2572. Vector3.CrossToRef = function (left, right, result) {
  2573. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2574. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2575. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2576. result.copyFrom(MathTmp.Vector3[0]);
  2577. };
  2578. /**
  2579. * Returns a new Vector3 as the normalization of the passed vector.
  2580. */
  2581. Vector3.Normalize = function (vector) {
  2582. var result = Vector3.Zero();
  2583. Vector3.NormalizeToRef(vector, result);
  2584. return result;
  2585. };
  2586. /**
  2587. * Sets the passed vector "result" with the normalization of the passed first vector.
  2588. */
  2589. Vector3.NormalizeToRef = function (vector, result) {
  2590. result.copyFrom(vector);
  2591. result.normalize();
  2592. };
  2593. Vector3.Project = function (vector, world, transform, viewport) {
  2594. var cw = viewport.width;
  2595. var ch = viewport.height;
  2596. var cx = viewport.x;
  2597. var cy = viewport.y;
  2598. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2599. 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);
  2600. var matrix = MathTmp.Matrix[0];
  2601. world.multiplyToRef(transform, matrix);
  2602. matrix.multiplyToRef(viewportMatrix, matrix);
  2603. return Vector3.TransformCoordinates(vector, matrix);
  2604. };
  2605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2606. var matrix = MathTmp.Matrix[0];
  2607. world.multiplyToRef(transform, matrix);
  2608. matrix.invert();
  2609. source.x = source.x / viewportWidth * 2 - 1;
  2610. source.y = -(source.y / viewportHeight * 2 - 1);
  2611. var vector = Vector3.TransformCoordinates(source, matrix);
  2612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2614. vector = vector.scale(1.0 / num);
  2615. }
  2616. return vector;
  2617. };
  2618. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2619. var result = Vector3.Zero();
  2620. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2621. return result;
  2622. };
  2623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2625. };
  2626. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2627. var matrix = MathTmp.Matrix[0];
  2628. world.multiplyToRef(view, matrix);
  2629. matrix.multiplyToRef(projection, matrix);
  2630. matrix.invert();
  2631. var screenSource = MathTmp.Vector3[0];
  2632. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2633. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2634. screenSource.z = 2 * sourceZ - 1.0;
  2635. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2636. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2637. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2638. result.scaleInPlace(1.0 / num);
  2639. }
  2640. };
  2641. Vector3.Minimize = function (left, right) {
  2642. var min = left.clone();
  2643. min.MinimizeInPlace(right);
  2644. return min;
  2645. };
  2646. Vector3.Maximize = function (left, right) {
  2647. var max = left.clone();
  2648. max.MaximizeInPlace(right);
  2649. return max;
  2650. };
  2651. /**
  2652. * Returns the distance (float) between the vectors "value1" and "value2".
  2653. */
  2654. Vector3.Distance = function (value1, value2) {
  2655. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2656. };
  2657. /**
  2658. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2659. */
  2660. Vector3.DistanceSquared = function (value1, value2) {
  2661. var x = value1.x - value2.x;
  2662. var y = value1.y - value2.y;
  2663. var z = value1.z - value2.z;
  2664. return (x * x) + (y * y) + (z * z);
  2665. };
  2666. /**
  2667. * Returns a new Vector3 located at the center between "value1" and "value2".
  2668. */
  2669. Vector3.Center = function (value1, value2) {
  2670. var center = value1.add(value2);
  2671. center.scaleInPlace(0.5);
  2672. return center;
  2673. };
  2674. /**
  2675. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2676. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2677. * to something in order to rotate it from its local system to the given target system.
  2678. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2679. * Returns a new Vector3.
  2680. */
  2681. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2682. var rotation = Vector3.Zero();
  2683. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2684. return rotation;
  2685. };
  2686. /**
  2687. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2688. */
  2689. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2690. var quat = MathTmp.Quaternion[0];
  2691. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2692. quat.toEulerAnglesToRef(ref);
  2693. };
  2694. return Vector3;
  2695. }());
  2696. BABYLON.Vector3 = Vector3;
  2697. //Vector4 class created for EulerAngle class conversion to Quaternion
  2698. var Vector4 = /** @class */ (function () {
  2699. /**
  2700. * Creates a Vector4 object from the passed floats.
  2701. */
  2702. function Vector4(x, y, z, w) {
  2703. this.x = x;
  2704. this.y = y;
  2705. this.z = z;
  2706. this.w = w;
  2707. }
  2708. /**
  2709. * Returns the string with the Vector4 coordinates.
  2710. */
  2711. Vector4.prototype.toString = function () {
  2712. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2713. };
  2714. /**
  2715. * Returns the string "Vector4".
  2716. */
  2717. Vector4.prototype.getClassName = function () {
  2718. return "Vector4";
  2719. };
  2720. /**
  2721. * Returns the Vector4 hash code.
  2722. */
  2723. Vector4.prototype.getHashCode = function () {
  2724. var hash = this.x || 0;
  2725. hash = (hash * 397) ^ (this.y || 0);
  2726. hash = (hash * 397) ^ (this.z || 0);
  2727. hash = (hash * 397) ^ (this.w || 0);
  2728. return hash;
  2729. };
  2730. // Operators
  2731. /**
  2732. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2733. */
  2734. Vector4.prototype.asArray = function () {
  2735. var result = new Array();
  2736. this.toArray(result, 0);
  2737. return result;
  2738. };
  2739. /**
  2740. * Populates the passed array from the passed index with the Vector4 coordinates.
  2741. * Returns the Vector4.
  2742. */
  2743. Vector4.prototype.toArray = function (array, index) {
  2744. if (index === undefined) {
  2745. index = 0;
  2746. }
  2747. array[index] = this.x;
  2748. array[index + 1] = this.y;
  2749. array[index + 2] = this.z;
  2750. array[index + 3] = this.w;
  2751. return this;
  2752. };
  2753. /**
  2754. * Adds the passed vector to the current Vector4.
  2755. * Returns the updated Vector4.
  2756. */
  2757. Vector4.prototype.addInPlace = function (otherVector) {
  2758. this.x += otherVector.x;
  2759. this.y += otherVector.y;
  2760. this.z += otherVector.z;
  2761. this.w += otherVector.w;
  2762. return this;
  2763. };
  2764. /**
  2765. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2766. */
  2767. Vector4.prototype.add = function (otherVector) {
  2768. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2769. };
  2770. /**
  2771. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2772. * Returns the current Vector4.
  2773. */
  2774. Vector4.prototype.addToRef = function (otherVector, result) {
  2775. result.x = this.x + otherVector.x;
  2776. result.y = this.y + otherVector.y;
  2777. result.z = this.z + otherVector.z;
  2778. result.w = this.w + otherVector.w;
  2779. return this;
  2780. };
  2781. /**
  2782. * Subtract in place the passed vector from the current Vector4.
  2783. * Returns the updated Vector4.
  2784. */
  2785. Vector4.prototype.subtractInPlace = function (otherVector) {
  2786. this.x -= otherVector.x;
  2787. this.y -= otherVector.y;
  2788. this.z -= otherVector.z;
  2789. this.w -= otherVector.w;
  2790. return this;
  2791. };
  2792. /**
  2793. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2794. */
  2795. Vector4.prototype.subtract = function (otherVector) {
  2796. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2797. };
  2798. /**
  2799. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2800. * Returns the current Vector4.
  2801. */
  2802. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2803. result.x = this.x - otherVector.x;
  2804. result.y = this.y - otherVector.y;
  2805. result.z = this.z - otherVector.z;
  2806. result.w = this.w - otherVector.w;
  2807. return this;
  2808. };
  2809. /**
  2810. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2811. */
  2812. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2813. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2817. * Returns the current Vector4.
  2818. */
  2819. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2820. result.x = this.x - x;
  2821. result.y = this.y - y;
  2822. result.z = this.z - z;
  2823. result.w = this.w - w;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2828. */
  2829. Vector4.prototype.negate = function () {
  2830. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2831. };
  2832. /**
  2833. * Multiplies the current Vector4 coordinates by scale (float).
  2834. * Returns the updated Vector4.
  2835. */
  2836. Vector4.prototype.scaleInPlace = function (scale) {
  2837. this.x *= scale;
  2838. this.y *= scale;
  2839. this.z *= scale;
  2840. this.w *= scale;
  2841. return this;
  2842. };
  2843. /**
  2844. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2845. */
  2846. Vector4.prototype.scale = function (scale) {
  2847. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2848. };
  2849. /**
  2850. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2851. * Returns the current Vector4.
  2852. */
  2853. Vector4.prototype.scaleToRef = function (scale, result) {
  2854. result.x = this.x * scale;
  2855. result.y = this.y * scale;
  2856. result.z = this.z * scale;
  2857. result.w = this.w * scale;
  2858. return this;
  2859. };
  2860. /**
  2861. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2862. */
  2863. Vector4.prototype.equals = function (otherVector) {
  2864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2865. };
  2866. /**
  2867. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2868. */
  2869. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2870. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2871. return otherVector
  2872. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2873. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2874. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2875. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2876. };
  2877. /**
  2878. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2879. */
  2880. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2881. return this.x === x && this.y === y && this.z === z && this.w === w;
  2882. };
  2883. /**
  2884. * Multiplies in place the current Vector4 by the passed one.
  2885. * Returns the updated Vector4.
  2886. */
  2887. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2888. this.x *= otherVector.x;
  2889. this.y *= otherVector.y;
  2890. this.z *= otherVector.z;
  2891. this.w *= otherVector.w;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2896. */
  2897. Vector4.prototype.multiply = function (otherVector) {
  2898. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2899. };
  2900. /**
  2901. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2902. * Returns the current Vector4.
  2903. */
  2904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2905. result.x = this.x * otherVector.x;
  2906. result.y = this.y * otherVector.y;
  2907. result.z = this.z * otherVector.z;
  2908. result.w = this.w * otherVector.w;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2913. */
  2914. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2915. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2916. };
  2917. /**
  2918. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2919. */
  2920. Vector4.prototype.divide = function (otherVector) {
  2921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2922. };
  2923. /**
  2924. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2925. * Returns the current Vector4.
  2926. */
  2927. Vector4.prototype.divideToRef = function (otherVector, result) {
  2928. result.x = this.x / otherVector.x;
  2929. result.y = this.y / otherVector.y;
  2930. result.z = this.z / otherVector.z;
  2931. result.w = this.w / otherVector.w;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * Returns the updated Vector3.
  2937. */
  2938. Vector4.prototype.divideInPlace = function (otherVector) {
  2939. return this.divideToRef(otherVector, this);
  2940. };
  2941. /**
  2942. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2943. */
  2944. Vector4.prototype.MinimizeInPlace = function (other) {
  2945. if (other.x < this.x)
  2946. this.x = other.x;
  2947. if (other.y < this.y)
  2948. this.y = other.y;
  2949. if (other.z < this.z)
  2950. this.z = other.z;
  2951. if (other.w < this.w)
  2952. this.w = other.w;
  2953. return this;
  2954. };
  2955. /**
  2956. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2957. */
  2958. Vector4.prototype.MaximizeInPlace = function (other) {
  2959. if (other.x > this.x)
  2960. this.x = other.x;
  2961. if (other.y > this.y)
  2962. this.y = other.y;
  2963. if (other.z > this.z)
  2964. this.z = other.z;
  2965. if (other.w > this.w)
  2966. this.w = other.w;
  2967. return this;
  2968. };
  2969. // Properties
  2970. /**
  2971. * Returns the Vector4 length (float).
  2972. */
  2973. Vector4.prototype.length = function () {
  2974. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2975. };
  2976. /**
  2977. * Returns the Vector4 squared length (float).
  2978. */
  2979. Vector4.prototype.lengthSquared = function () {
  2980. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2981. };
  2982. // Methods
  2983. /**
  2984. * Normalizes in place the Vector4.
  2985. * Returns the updated Vector4.
  2986. */
  2987. Vector4.prototype.normalize = function () {
  2988. var len = this.length();
  2989. if (len === 0)
  2990. return this;
  2991. var num = 1.0 / len;
  2992. this.x *= num;
  2993. this.y *= num;
  2994. this.z *= num;
  2995. this.w *= num;
  2996. return this;
  2997. };
  2998. /**
  2999. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3000. */
  3001. Vector4.prototype.toVector3 = function () {
  3002. return new Vector3(this.x, this.y, this.z);
  3003. };
  3004. /**
  3005. * Returns a new Vector4 copied from the current one.
  3006. */
  3007. Vector4.prototype.clone = function () {
  3008. return new Vector4(this.x, this.y, this.z, this.w);
  3009. };
  3010. /**
  3011. * Updates the current Vector4 with the passed one coordinates.
  3012. * Returns the updated Vector4.
  3013. */
  3014. Vector4.prototype.copyFrom = function (source) {
  3015. this.x = source.x;
  3016. this.y = source.y;
  3017. this.z = source.z;
  3018. this.w = source.w;
  3019. return this;
  3020. };
  3021. /**
  3022. * Updates the current Vector4 coordinates with the passed floats.
  3023. * Returns the updated Vector4.
  3024. */
  3025. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3026. this.x = x;
  3027. this.y = y;
  3028. this.z = z;
  3029. this.w = w;
  3030. return this;
  3031. };
  3032. /**
  3033. * Updates the current Vector4 coordinates with the passed floats.
  3034. * Returns the updated Vector4.
  3035. */
  3036. Vector4.prototype.set = function (x, y, z, w) {
  3037. return this.copyFromFloats(x, y, z, w);
  3038. };
  3039. // Statics
  3040. /**
  3041. * Returns a new Vector4 set from the starting index of the passed array.
  3042. */
  3043. Vector4.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3048. };
  3049. /**
  3050. * Updates the passed vector "result" from the starting index of the passed array.
  3051. */
  3052. Vector4.FromArrayToRef = function (array, offset, result) {
  3053. result.x = array[offset];
  3054. result.y = array[offset + 1];
  3055. result.z = array[offset + 2];
  3056. result.w = array[offset + 3];
  3057. };
  3058. /**
  3059. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3060. */
  3061. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3062. Vector4.FromArrayToRef(array, offset, result);
  3063. };
  3064. /**
  3065. * Updates the passed vector "result" coordinates from the passed floats.
  3066. */
  3067. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3068. result.x = x;
  3069. result.y = y;
  3070. result.z = z;
  3071. result.w = w;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3075. */
  3076. Vector4.Zero = function () {
  3077. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3078. };
  3079. /**
  3080. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3081. */
  3082. Vector4.One = function () {
  3083. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3084. };
  3085. /**
  3086. * Returns a new normalized Vector4 from the passed one.
  3087. */
  3088. Vector4.Normalize = function (vector) {
  3089. var result = Vector4.Zero();
  3090. Vector4.NormalizeToRef(vector, result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Updates the passed vector "result" from the normalization of the passed one.
  3095. */
  3096. Vector4.NormalizeToRef = function (vector, result) {
  3097. result.copyFrom(vector);
  3098. result.normalize();
  3099. };
  3100. Vector4.Minimize = function (left, right) {
  3101. var min = left.clone();
  3102. min.MinimizeInPlace(right);
  3103. return min;
  3104. };
  3105. Vector4.Maximize = function (left, right) {
  3106. var max = left.clone();
  3107. max.MaximizeInPlace(right);
  3108. return max;
  3109. };
  3110. /**
  3111. * Returns the distance (float) between the vectors "value1" and "value2".
  3112. */
  3113. Vector4.Distance = function (value1, value2) {
  3114. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3115. };
  3116. /**
  3117. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3118. */
  3119. Vector4.DistanceSquared = function (value1, value2) {
  3120. var x = value1.x - value2.x;
  3121. var y = value1.y - value2.y;
  3122. var z = value1.z - value2.z;
  3123. var w = value1.w - value2.w;
  3124. return (x * x) + (y * y) + (z * z) + (w * w);
  3125. };
  3126. /**
  3127. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3128. */
  3129. Vector4.Center = function (value1, value2) {
  3130. var center = value1.add(value2);
  3131. center.scaleInPlace(0.5);
  3132. return center;
  3133. };
  3134. /**
  3135. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3136. * This methods computes transformed normalized direction vectors only.
  3137. */
  3138. Vector4.TransformNormal = function (vector, transformation) {
  3139. var result = Vector4.Zero();
  3140. Vector4.TransformNormalToRef(vector, transformation, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3145. * This methods computes transformed normalized direction vectors only.
  3146. */
  3147. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3148. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3149. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3150. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3151. result.x = x;
  3152. result.y = y;
  3153. result.z = z;
  3154. result.w = vector.w;
  3155. };
  3156. /**
  3157. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3158. * This methods computes transformed normalized direction vectors only.
  3159. */
  3160. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3161. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3162. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3163. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3164. result.w = w;
  3165. };
  3166. return Vector4;
  3167. }());
  3168. BABYLON.Vector4 = Vector4;
  3169. var Size = /** @class */ (function () {
  3170. /**
  3171. * Creates a Size object from the passed width and height (floats).
  3172. */
  3173. function Size(width, height) {
  3174. this.width = width;
  3175. this.height = height;
  3176. }
  3177. // Returns a string with the Size width and height.
  3178. Size.prototype.toString = function () {
  3179. return "{W: " + this.width + ", H: " + this.height + "}";
  3180. };
  3181. /**
  3182. * Returns the string "Size"
  3183. */
  3184. Size.prototype.getClassName = function () {
  3185. return "Size";
  3186. };
  3187. /**
  3188. * Returns the Size hash code.
  3189. */
  3190. Size.prototype.getHashCode = function () {
  3191. var hash = this.width || 0;
  3192. hash = (hash * 397) ^ (this.height || 0);
  3193. return hash;
  3194. };
  3195. /**
  3196. * Updates the current size from the passed one.
  3197. * Returns the updated Size.
  3198. */
  3199. Size.prototype.copyFrom = function (src) {
  3200. this.width = src.width;
  3201. this.height = src.height;
  3202. };
  3203. /**
  3204. * Updates in place the current Size from the passed floats.
  3205. * Returns the updated Size.
  3206. */
  3207. Size.prototype.copyFromFloats = function (width, height) {
  3208. this.width = width;
  3209. this.height = height;
  3210. return this;
  3211. };
  3212. /**
  3213. * Updates in place the current Size from the passed floats.
  3214. * Returns the updated Size.
  3215. */
  3216. Size.prototype.set = function (width, height) {
  3217. return this.copyFromFloats(width, height);
  3218. };
  3219. /**
  3220. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3221. */
  3222. Size.prototype.multiplyByFloats = function (w, h) {
  3223. return new Size(this.width * w, this.height * h);
  3224. };
  3225. /**
  3226. * Returns a new Size copied from the passed one.
  3227. */
  3228. Size.prototype.clone = function () {
  3229. return new Size(this.width, this.height);
  3230. };
  3231. /**
  3232. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3233. */
  3234. Size.prototype.equals = function (other) {
  3235. if (!other) {
  3236. return false;
  3237. }
  3238. return (this.width === other.width) && (this.height === other.height);
  3239. };
  3240. Object.defineProperty(Size.prototype, "surface", {
  3241. /**
  3242. * Returns the surface of the Size : width * height (float).
  3243. */
  3244. get: function () {
  3245. return this.width * this.height;
  3246. },
  3247. enumerable: true,
  3248. configurable: true
  3249. });
  3250. /**
  3251. * Returns a new Size set to (0.0, 0.0)
  3252. */
  3253. Size.Zero = function () {
  3254. return new Size(0.0, 0.0);
  3255. };
  3256. /**
  3257. * Returns a new Size set as the addition result of the current Size and the passed one.
  3258. */
  3259. Size.prototype.add = function (otherSize) {
  3260. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3261. return r;
  3262. };
  3263. /**
  3264. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3265. */
  3266. Size.prototype.subtract = function (otherSize) {
  3267. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3268. return r;
  3269. };
  3270. /**
  3271. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3272. */
  3273. Size.Lerp = function (start, end, amount) {
  3274. var w = start.width + ((end.width - start.width) * amount);
  3275. var h = start.height + ((end.height - start.height) * amount);
  3276. return new Size(w, h);
  3277. };
  3278. return Size;
  3279. }());
  3280. BABYLON.Size = Size;
  3281. var Quaternion = /** @class */ (function () {
  3282. /**
  3283. * Creates a new Quaternion from the passed floats.
  3284. */
  3285. function Quaternion(x, y, z, w) {
  3286. if (x === void 0) { x = 0.0; }
  3287. if (y === void 0) { y = 0.0; }
  3288. if (z === void 0) { z = 0.0; }
  3289. if (w === void 0) { w = 1.0; }
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. this.w = w;
  3294. }
  3295. /**
  3296. * Returns a string with the Quaternion coordinates.
  3297. */
  3298. Quaternion.prototype.toString = function () {
  3299. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3300. };
  3301. /**
  3302. * Returns the string "Quaternion".
  3303. */
  3304. Quaternion.prototype.getClassName = function () {
  3305. return "Quaternion";
  3306. };
  3307. /**
  3308. * Returns the Quaternion hash code.
  3309. */
  3310. Quaternion.prototype.getHashCode = function () {
  3311. var hash = this.x || 0;
  3312. hash = (hash * 397) ^ (this.y || 0);
  3313. hash = (hash * 397) ^ (this.z || 0);
  3314. hash = (hash * 397) ^ (this.w || 0);
  3315. return hash;
  3316. };
  3317. /**
  3318. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3319. */
  3320. Quaternion.prototype.asArray = function () {
  3321. return [this.x, this.y, this.z, this.w];
  3322. };
  3323. /**
  3324. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3325. */
  3326. Quaternion.prototype.equals = function (otherQuaternion) {
  3327. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3328. };
  3329. /**
  3330. * Returns a new Quaternion copied from the current one.
  3331. */
  3332. Quaternion.prototype.clone = function () {
  3333. return new Quaternion(this.x, this.y, this.z, this.w);
  3334. };
  3335. /**
  3336. * Updates the current Quaternion from the passed one coordinates.
  3337. * Returns the updated Quaterion.
  3338. */
  3339. Quaternion.prototype.copyFrom = function (other) {
  3340. this.x = other.x;
  3341. this.y = other.y;
  3342. this.z = other.z;
  3343. this.w = other.w;
  3344. return this;
  3345. };
  3346. /**
  3347. * Updates the current Quaternion from the passed float coordinates.
  3348. * Returns the updated Quaterion.
  3349. */
  3350. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3351. this.x = x;
  3352. this.y = y;
  3353. this.z = z;
  3354. this.w = w;
  3355. return this;
  3356. };
  3357. /**
  3358. * Updates the current Quaternion from the passed float coordinates.
  3359. * Returns the updated Quaterion.
  3360. */
  3361. Quaternion.prototype.set = function (x, y, z, w) {
  3362. return this.copyFromFloats(x, y, z, w);
  3363. };
  3364. /**
  3365. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3366. */
  3367. Quaternion.prototype.add = function (other) {
  3368. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3369. };
  3370. /**
  3371. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3372. */
  3373. Quaternion.prototype.subtract = function (other) {
  3374. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3375. };
  3376. /**
  3377. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3378. */
  3379. Quaternion.prototype.scale = function (value) {
  3380. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3381. };
  3382. /**
  3383. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3384. */
  3385. Quaternion.prototype.multiply = function (q1) {
  3386. var result = new Quaternion(0, 0, 0, 1.0);
  3387. this.multiplyToRef(q1, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3392. * Returns the current Quaternion.
  3393. */
  3394. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3395. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3396. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3397. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3398. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3399. result.copyFromFloats(x, y, z, w);
  3400. return this;
  3401. };
  3402. /**
  3403. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3404. * Returns the updated Quaternion.
  3405. */
  3406. Quaternion.prototype.multiplyInPlace = function (q1) {
  3407. this.multiplyToRef(q1, this);
  3408. return this;
  3409. };
  3410. /**
  3411. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3412. * Returns the current Quaternion.
  3413. */
  3414. Quaternion.prototype.conjugateToRef = function (ref) {
  3415. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3416. return this;
  3417. };
  3418. /**
  3419. * Conjugates in place the current Quaternion.
  3420. * Returns the updated Quaternion.
  3421. */
  3422. Quaternion.prototype.conjugateInPlace = function () {
  3423. this.x *= -1;
  3424. this.y *= -1;
  3425. this.z *= -1;
  3426. return this;
  3427. };
  3428. /**
  3429. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3430. */
  3431. Quaternion.prototype.conjugate = function () {
  3432. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3433. return result;
  3434. };
  3435. /**
  3436. * Returns the Quaternion length (float).
  3437. */
  3438. Quaternion.prototype.length = function () {
  3439. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3440. };
  3441. /**
  3442. * Normalize in place the current Quaternion.
  3443. * Returns the updated Quaternion.
  3444. */
  3445. Quaternion.prototype.normalize = function () {
  3446. var length = 1.0 / this.length();
  3447. this.x *= length;
  3448. this.y *= length;
  3449. this.z *= length;
  3450. this.w *= length;
  3451. return this;
  3452. };
  3453. /**
  3454. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3455. */
  3456. Quaternion.prototype.toEulerAngles = function (order) {
  3457. if (order === void 0) { order = "YZX"; }
  3458. var result = Vector3.Zero();
  3459. this.toEulerAnglesToRef(result, order);
  3460. return result;
  3461. };
  3462. /**
  3463. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3464. * Returns the current Quaternion.
  3465. */
  3466. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3467. if (order === void 0) { order = "YZX"; }
  3468. var qz = this.z;
  3469. var qx = this.x;
  3470. var qy = this.y;
  3471. var qw = this.w;
  3472. var sqw = qw * qw;
  3473. var sqz = qz * qz;
  3474. var sqx = qx * qx;
  3475. var sqy = qy * qy;
  3476. var zAxisY = qy * qz - qx * qw;
  3477. var limit = .4999999;
  3478. if (zAxisY < -limit) {
  3479. result.y = 2 * Math.atan2(qy, qw);
  3480. result.x = Math.PI / 2;
  3481. result.z = 0;
  3482. }
  3483. else if (zAxisY > limit) {
  3484. result.y = 2 * Math.atan2(qy, qw);
  3485. result.x = -Math.PI / 2;
  3486. result.z = 0;
  3487. }
  3488. else {
  3489. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3490. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3491. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3492. }
  3493. return this;
  3494. };
  3495. /**
  3496. * Updates the passed rotation matrix with the current Quaternion values.
  3497. * Returns the current Quaternion.
  3498. */
  3499. Quaternion.prototype.toRotationMatrix = function (result) {
  3500. var xx = this.x * this.x;
  3501. var yy = this.y * this.y;
  3502. var zz = this.z * this.z;
  3503. var xy = this.x * this.y;
  3504. var zw = this.z * this.w;
  3505. var zx = this.z * this.x;
  3506. var yw = this.y * this.w;
  3507. var yz = this.y * this.z;
  3508. var xw = this.x * this.w;
  3509. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3510. result.m[1] = 2.0 * (xy + zw);
  3511. result.m[2] = 2.0 * (zx - yw);
  3512. result.m[3] = 0;
  3513. result.m[4] = 2.0 * (xy - zw);
  3514. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3515. result.m[6] = 2.0 * (yz + xw);
  3516. result.m[7] = 0;
  3517. result.m[8] = 2.0 * (zx + yw);
  3518. result.m[9] = 2.0 * (yz - xw);
  3519. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3520. result.m[11] = 0;
  3521. result.m[12] = 0;
  3522. result.m[13] = 0;
  3523. result.m[14] = 0;
  3524. result.m[15] = 1.0;
  3525. result._markAsUpdated();
  3526. return this;
  3527. };
  3528. /**
  3529. * Updates the current Quaternion from the passed rotation matrix values.
  3530. * Returns the updated Quaternion.
  3531. */
  3532. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3533. Quaternion.FromRotationMatrixToRef(matrix, this);
  3534. return this;
  3535. };
  3536. // Statics
  3537. /**
  3538. * Returns a new Quaternion set from the passed rotation matrix values.
  3539. */
  3540. Quaternion.FromRotationMatrix = function (matrix) {
  3541. var result = new Quaternion();
  3542. Quaternion.FromRotationMatrixToRef(matrix, result);
  3543. return result;
  3544. };
  3545. /**
  3546. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3547. */
  3548. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3549. var data = matrix.m;
  3550. var m11 = data[0], m12 = data[4], m13 = data[8];
  3551. var m21 = data[1], m22 = data[5], m23 = data[9];
  3552. var m31 = data[2], m32 = data[6], m33 = data[10];
  3553. var trace = m11 + m22 + m33;
  3554. var s;
  3555. if (trace > 0) {
  3556. s = 0.5 / Math.sqrt(trace + 1.0);
  3557. result.w = 0.25 / s;
  3558. result.x = (m32 - m23) * s;
  3559. result.y = (m13 - m31) * s;
  3560. result.z = (m21 - m12) * s;
  3561. }
  3562. else if (m11 > m22 && m11 > m33) {
  3563. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3564. result.w = (m32 - m23) / s;
  3565. result.x = 0.25 * s;
  3566. result.y = (m12 + m21) / s;
  3567. result.z = (m13 + m31) / s;
  3568. }
  3569. else if (m22 > m33) {
  3570. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3571. result.w = (m13 - m31) / s;
  3572. result.x = (m12 + m21) / s;
  3573. result.y = 0.25 * s;
  3574. result.z = (m23 + m32) / s;
  3575. }
  3576. else {
  3577. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3578. result.w = (m21 - m12) / s;
  3579. result.x = (m13 + m31) / s;
  3580. result.y = (m23 + m32) / s;
  3581. result.z = 0.25 * s;
  3582. }
  3583. };
  3584. /**
  3585. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3586. */
  3587. Quaternion.Zero = function () {
  3588. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3589. };
  3590. /**
  3591. * Returns a new Quaternion as the inverted current Quaternion.
  3592. */
  3593. Quaternion.Inverse = function (q) {
  3594. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3595. };
  3596. /**
  3597. * Returns the identity Quaternion.
  3598. */
  3599. Quaternion.Identity = function () {
  3600. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3601. };
  3602. Quaternion.IsIdentity = function (quaternion) {
  3603. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3604. };
  3605. /**
  3606. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3607. */
  3608. Quaternion.RotationAxis = function (axis, angle) {
  3609. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3610. };
  3611. /**
  3612. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3613. */
  3614. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3615. var sin = Math.sin(angle / 2);
  3616. axis.normalize();
  3617. result.w = Math.cos(angle / 2);
  3618. result.x = axis.x * sin;
  3619. result.y = axis.y * sin;
  3620. result.z = axis.z * sin;
  3621. return result;
  3622. };
  3623. /**
  3624. * Retuns a new Quaternion set from the starting index of the passed array.
  3625. */
  3626. Quaternion.FromArray = function (array, offset) {
  3627. if (!offset) {
  3628. offset = 0;
  3629. }
  3630. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3631. };
  3632. /**
  3633. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3634. */
  3635. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3636. var q = new Quaternion();
  3637. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3638. return q;
  3639. };
  3640. /**
  3641. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3642. */
  3643. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3644. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3645. var halfRoll = roll * 0.5;
  3646. var halfPitch = pitch * 0.5;
  3647. var halfYaw = yaw * 0.5;
  3648. var sinRoll = Math.sin(halfRoll);
  3649. var cosRoll = Math.cos(halfRoll);
  3650. var sinPitch = Math.sin(halfPitch);
  3651. var cosPitch = Math.cos(halfPitch);
  3652. var sinYaw = Math.sin(halfYaw);
  3653. var cosYaw = Math.cos(halfYaw);
  3654. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3655. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3656. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3657. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3658. };
  3659. /**
  3660. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3661. */
  3662. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3663. var result = new Quaternion();
  3664. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3665. return result;
  3666. };
  3667. /**
  3668. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3669. */
  3670. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3671. // Produces a quaternion from Euler angles in the z-x-z orientation
  3672. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3673. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3674. var halfBeta = beta * 0.5;
  3675. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3676. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3677. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3678. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3679. };
  3680. /**
  3681. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3682. * cf to Vector3.RotationFromAxis() documentation.
  3683. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3684. */
  3685. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3686. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3687. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3688. return quat;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3692. * cf to Vector3.RotationFromAxis() documentation.
  3693. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3694. */
  3695. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3696. var rotMat = MathTmp.Matrix[0];
  3697. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3698. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3699. };
  3700. Quaternion.Slerp = function (left, right, amount) {
  3701. var result = Quaternion.Identity();
  3702. Quaternion.SlerpToRef(left, right, amount, result);
  3703. return result;
  3704. };
  3705. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3706. var num2;
  3707. var num3;
  3708. var num = amount;
  3709. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3710. var flag = false;
  3711. if (num4 < 0) {
  3712. flag = true;
  3713. num4 = -num4;
  3714. }
  3715. if (num4 > 0.999999) {
  3716. num3 = 1 - num;
  3717. num2 = flag ? -num : num;
  3718. }
  3719. else {
  3720. var num5 = Math.acos(num4);
  3721. var num6 = (1.0 / Math.sin(num5));
  3722. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3723. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3724. }
  3725. result.x = (num3 * left.x) + (num2 * right.x);
  3726. result.y = (num3 * left.y) + (num2 * right.y);
  3727. result.z = (num3 * left.z) + (num2 * right.z);
  3728. result.w = (num3 * left.w) + (num2 * right.w);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3732. */
  3733. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3734. var squared = amount * amount;
  3735. var cubed = amount * squared;
  3736. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3737. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3738. var part3 = (cubed - (2.0 * squared)) + amount;
  3739. var part4 = cubed - squared;
  3740. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3741. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3742. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3743. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3744. return new Quaternion(x, y, z, w);
  3745. };
  3746. return Quaternion;
  3747. }());
  3748. BABYLON.Quaternion = Quaternion;
  3749. var Matrix = /** @class */ (function () {
  3750. function Matrix() {
  3751. this._isIdentity = false;
  3752. this._isIdentityDirty = true;
  3753. this.m = new Float32Array(16);
  3754. this._markAsUpdated();
  3755. }
  3756. Matrix.prototype._markAsUpdated = function () {
  3757. this.updateFlag = Matrix._updateFlagSeed++;
  3758. this._isIdentityDirty = true;
  3759. };
  3760. // Properties
  3761. /**
  3762. * Boolean : True is the matrix is the identity matrix
  3763. */
  3764. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3765. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3766. if (this._isIdentityDirty) {
  3767. this._isIdentityDirty = false;
  3768. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3769. this._isIdentity = false;
  3770. }
  3771. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3772. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3773. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3774. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3775. this._isIdentity = false;
  3776. }
  3777. else {
  3778. this._isIdentity = true;
  3779. }
  3780. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3781. this._isIdentity = false;
  3782. }
  3783. }
  3784. return this._isIdentity;
  3785. };
  3786. /**
  3787. * Returns the matrix determinant (float).
  3788. */
  3789. Matrix.prototype.determinant = function () {
  3790. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3791. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3792. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3793. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3794. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3795. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3796. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3797. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3798. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3799. };
  3800. // Methods
  3801. /**
  3802. * Returns the matrix underlying array.
  3803. */
  3804. Matrix.prototype.toArray = function () {
  3805. return this.m;
  3806. };
  3807. /**
  3808. * Returns the matrix underlying array.
  3809. */
  3810. Matrix.prototype.asArray = function () {
  3811. return this.toArray();
  3812. };
  3813. /**
  3814. * Inverts in place the Matrix.
  3815. * Returns the Matrix inverted.
  3816. */
  3817. Matrix.prototype.invert = function () {
  3818. this.invertToRef(this);
  3819. return this;
  3820. };
  3821. /**
  3822. * Sets all the matrix elements to zero.
  3823. * Returns the Matrix.
  3824. */
  3825. Matrix.prototype.reset = function () {
  3826. for (var index = 0; index < 16; index++) {
  3827. this.m[index] = 0.0;
  3828. }
  3829. this._markAsUpdated();
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3834. */
  3835. Matrix.prototype.add = function (other) {
  3836. var result = new Matrix();
  3837. this.addToRef(other, result);
  3838. return result;
  3839. };
  3840. /**
  3841. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3842. * Returns the Matrix.
  3843. */
  3844. Matrix.prototype.addToRef = function (other, result) {
  3845. for (var index = 0; index < 16; index++) {
  3846. result.m[index] = this.m[index] + other.m[index];
  3847. }
  3848. result._markAsUpdated();
  3849. return this;
  3850. };
  3851. /**
  3852. * Adds in place the passed matrix to the current Matrix.
  3853. * Returns the updated Matrix.
  3854. */
  3855. Matrix.prototype.addToSelf = function (other) {
  3856. for (var index = 0; index < 16; index++) {
  3857. this.m[index] += other.m[index];
  3858. }
  3859. this._markAsUpdated();
  3860. return this;
  3861. };
  3862. /**
  3863. * Sets the passed matrix with the current inverted Matrix.
  3864. * Returns the unmodified current Matrix.
  3865. */
  3866. Matrix.prototype.invertToRef = function (other) {
  3867. var l1 = this.m[0];
  3868. var l2 = this.m[1];
  3869. var l3 = this.m[2];
  3870. var l4 = this.m[3];
  3871. var l5 = this.m[4];
  3872. var l6 = this.m[5];
  3873. var l7 = this.m[6];
  3874. var l8 = this.m[7];
  3875. var l9 = this.m[8];
  3876. var l10 = this.m[9];
  3877. var l11 = this.m[10];
  3878. var l12 = this.m[11];
  3879. var l13 = this.m[12];
  3880. var l14 = this.m[13];
  3881. var l15 = this.m[14];
  3882. var l16 = this.m[15];
  3883. var l17 = (l11 * l16) - (l12 * l15);
  3884. var l18 = (l10 * l16) - (l12 * l14);
  3885. var l19 = (l10 * l15) - (l11 * l14);
  3886. var l20 = (l9 * l16) - (l12 * l13);
  3887. var l21 = (l9 * l15) - (l11 * l13);
  3888. var l22 = (l9 * l14) - (l10 * l13);
  3889. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3890. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3891. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3892. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3893. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3894. var l28 = (l7 * l16) - (l8 * l15);
  3895. var l29 = (l6 * l16) - (l8 * l14);
  3896. var l30 = (l6 * l15) - (l7 * l14);
  3897. var l31 = (l5 * l16) - (l8 * l13);
  3898. var l32 = (l5 * l15) - (l7 * l13);
  3899. var l33 = (l5 * l14) - (l6 * l13);
  3900. var l34 = (l7 * l12) - (l8 * l11);
  3901. var l35 = (l6 * l12) - (l8 * l10);
  3902. var l36 = (l6 * l11) - (l7 * l10);
  3903. var l37 = (l5 * l12) - (l8 * l9);
  3904. var l38 = (l5 * l11) - (l7 * l9);
  3905. var l39 = (l5 * l10) - (l6 * l9);
  3906. other.m[0] = l23 * l27;
  3907. other.m[4] = l24 * l27;
  3908. other.m[8] = l25 * l27;
  3909. other.m[12] = l26 * l27;
  3910. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3911. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3912. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3913. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3914. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3915. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3916. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3917. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3918. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3919. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3920. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3921. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3922. other._markAsUpdated();
  3923. return this;
  3924. };
  3925. /**
  3926. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3927. * Returns the updated Matrix.
  3928. */
  3929. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3930. this.m[12] = x;
  3931. this.m[13] = y;
  3932. this.m[14] = z;
  3933. this._markAsUpdated();
  3934. return this;
  3935. };
  3936. /**
  3937. * Inserts the translation vector in the current Matrix.
  3938. * Returns the updated Matrix.
  3939. */
  3940. Matrix.prototype.setTranslation = function (vector3) {
  3941. this.m[12] = vector3.x;
  3942. this.m[13] = vector3.y;
  3943. this.m[14] = vector3.z;
  3944. this._markAsUpdated();
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector3 as the extracted translation from the Matrix.
  3949. */
  3950. Matrix.prototype.getTranslation = function () {
  3951. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3952. };
  3953. /**
  3954. * Fill a Vector3 with the extracted translation from the Matrix.
  3955. */
  3956. Matrix.prototype.getTranslationToRef = function (result) {
  3957. result.x = this.m[12];
  3958. result.y = this.m[13];
  3959. result.z = this.m[14];
  3960. return this;
  3961. };
  3962. /**
  3963. * Remove rotation and scaling part from the Matrix.
  3964. * Returns the updated Matrix.
  3965. */
  3966. Matrix.prototype.removeRotationAndScaling = function () {
  3967. this.setRowFromFloats(0, 1, 0, 0, 0);
  3968. this.setRowFromFloats(1, 0, 1, 0, 0);
  3969. this.setRowFromFloats(2, 0, 0, 1, 0);
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3974. */
  3975. Matrix.prototype.multiply = function (other) {
  3976. var result = new Matrix();
  3977. this.multiplyToRef(other, result);
  3978. return result;
  3979. };
  3980. /**
  3981. * Updates the current Matrix from the passed one values.
  3982. * Returns the updated Matrix.
  3983. */
  3984. Matrix.prototype.copyFrom = function (other) {
  3985. for (var index = 0; index < 16; index++) {
  3986. this.m[index] = other.m[index];
  3987. }
  3988. this._markAsUpdated();
  3989. return this;
  3990. };
  3991. /**
  3992. * Populates the passed array from the starting index with the Matrix values.
  3993. * Returns the Matrix.
  3994. */
  3995. Matrix.prototype.copyToArray = function (array, offset) {
  3996. if (offset === void 0) { offset = 0; }
  3997. for (var index = 0; index < 16; index++) {
  3998. array[offset + index] = this.m[index];
  3999. }
  4000. return this;
  4001. };
  4002. /**
  4003. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4004. */
  4005. Matrix.prototype.multiplyToRef = function (other, result) {
  4006. this.multiplyToArray(other, result.m, 0);
  4007. result._markAsUpdated();
  4008. return this;
  4009. };
  4010. /**
  4011. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4012. */
  4013. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4014. var tm0 = this.m[0];
  4015. var tm1 = this.m[1];
  4016. var tm2 = this.m[2];
  4017. var tm3 = this.m[3];
  4018. var tm4 = this.m[4];
  4019. var tm5 = this.m[5];
  4020. var tm6 = this.m[6];
  4021. var tm7 = this.m[7];
  4022. var tm8 = this.m[8];
  4023. var tm9 = this.m[9];
  4024. var tm10 = this.m[10];
  4025. var tm11 = this.m[11];
  4026. var tm12 = this.m[12];
  4027. var tm13 = this.m[13];
  4028. var tm14 = this.m[14];
  4029. var tm15 = this.m[15];
  4030. var om0 = other.m[0];
  4031. var om1 = other.m[1];
  4032. var om2 = other.m[2];
  4033. var om3 = other.m[3];
  4034. var om4 = other.m[4];
  4035. var om5 = other.m[5];
  4036. var om6 = other.m[6];
  4037. var om7 = other.m[7];
  4038. var om8 = other.m[8];
  4039. var om9 = other.m[9];
  4040. var om10 = other.m[10];
  4041. var om11 = other.m[11];
  4042. var om12 = other.m[12];
  4043. var om13 = other.m[13];
  4044. var om14 = other.m[14];
  4045. var om15 = other.m[15];
  4046. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4047. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4048. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4049. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4050. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4051. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4052. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4053. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4054. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4055. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4056. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4057. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4058. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4059. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4060. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4061. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4062. return this;
  4063. };
  4064. /**
  4065. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4066. */
  4067. Matrix.prototype.equals = function (value) {
  4068. return value &&
  4069. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4070. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4071. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4072. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4073. };
  4074. /**
  4075. * Returns a new Matrix from the current Matrix.
  4076. */
  4077. Matrix.prototype.clone = function () {
  4078. 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]);
  4079. };
  4080. /**
  4081. * Returns the string "Matrix"
  4082. */
  4083. Matrix.prototype.getClassName = function () {
  4084. return "Matrix";
  4085. };
  4086. /**
  4087. * Returns the Matrix hash code.
  4088. */
  4089. Matrix.prototype.getHashCode = function () {
  4090. var hash = this.m[0] || 0;
  4091. for (var i = 1; i < 16; i++) {
  4092. hash = (hash * 397) ^ (this.m[i] || 0);
  4093. }
  4094. return hash;
  4095. };
  4096. /**
  4097. * Decomposes the current Matrix into :
  4098. * - a scale vector3 passed as a reference to update,
  4099. * - a rotation quaternion passed as a reference to update,
  4100. * - a translation vector3 passed as a reference to update.
  4101. * Returns the boolean `true`.
  4102. */
  4103. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4104. translation.x = this.m[12];
  4105. translation.y = this.m[13];
  4106. translation.z = this.m[14];
  4107. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4108. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4109. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4110. if (this.determinant() <= 0) {
  4111. scale.y *= -1;
  4112. }
  4113. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4114. rotation.x = 0;
  4115. rotation.y = 0;
  4116. rotation.z = 0;
  4117. rotation.w = 1;
  4118. return false;
  4119. }
  4120. 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]);
  4121. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4122. return true;
  4123. };
  4124. /**
  4125. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4126. */
  4127. Matrix.prototype.getRotationMatrix = function () {
  4128. var result = Matrix.Identity();
  4129. this.getRotationMatrixToRef(result);
  4130. return result;
  4131. };
  4132. /**
  4133. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4134. * Returns the current Matrix.
  4135. */
  4136. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4137. var m = this.m;
  4138. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4139. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4140. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4141. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4142. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4143. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4144. 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);
  4145. return this;
  4146. };
  4147. // Statics
  4148. /**
  4149. * Returns a new Matrix set from the starting index of the passed array.
  4150. */
  4151. Matrix.FromArray = function (array, offset) {
  4152. var result = new Matrix();
  4153. if (!offset) {
  4154. offset = 0;
  4155. }
  4156. Matrix.FromArrayToRef(array, offset, result);
  4157. return result;
  4158. };
  4159. /**
  4160. * Sets the passed "result" matrix from the starting index of the passed array.
  4161. */
  4162. Matrix.FromArrayToRef = function (array, offset, result) {
  4163. for (var index = 0; index < 16; index++) {
  4164. result.m[index] = array[index + offset];
  4165. }
  4166. result._markAsUpdated();
  4167. };
  4168. /**
  4169. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4170. */
  4171. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4172. for (var index = 0; index < 16; index++) {
  4173. result.m[index] = array[index + offset] * scale;
  4174. }
  4175. result._markAsUpdated();
  4176. };
  4177. /**
  4178. * Sets the passed matrix "result" with the 16 passed floats.
  4179. */
  4180. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4181. result.m[0] = initialM11;
  4182. result.m[1] = initialM12;
  4183. result.m[2] = initialM13;
  4184. result.m[3] = initialM14;
  4185. result.m[4] = initialM21;
  4186. result.m[5] = initialM22;
  4187. result.m[6] = initialM23;
  4188. result.m[7] = initialM24;
  4189. result.m[8] = initialM31;
  4190. result.m[9] = initialM32;
  4191. result.m[10] = initialM33;
  4192. result.m[11] = initialM34;
  4193. result.m[12] = initialM41;
  4194. result.m[13] = initialM42;
  4195. result.m[14] = initialM43;
  4196. result.m[15] = initialM44;
  4197. result._markAsUpdated();
  4198. };
  4199. /**
  4200. * Returns the index-th row of the current matrix as a new Vector4.
  4201. */
  4202. Matrix.prototype.getRow = function (index) {
  4203. if (index < 0 || index > 3) {
  4204. return null;
  4205. }
  4206. var i = index * 4;
  4207. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4208. };
  4209. /**
  4210. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.setRow = function (index, row) {
  4214. if (index < 0 || index > 3) {
  4215. return this;
  4216. }
  4217. var i = index * 4;
  4218. this.m[i + 0] = row.x;
  4219. this.m[i + 1] = row.y;
  4220. this.m[i + 2] = row.z;
  4221. this.m[i + 3] = row.w;
  4222. this._markAsUpdated();
  4223. return this;
  4224. };
  4225. /**
  4226. * Compute the transpose of the matrix.
  4227. * Returns a new Matrix.
  4228. */
  4229. Matrix.prototype.transpose = function () {
  4230. return Matrix.Transpose(this);
  4231. };
  4232. /**
  4233. * Compute the transpose of the matrix.
  4234. * Returns the current matrix.
  4235. */
  4236. Matrix.prototype.transposeToRef = function (result) {
  4237. Matrix.TransposeToRef(this, result);
  4238. return this;
  4239. };
  4240. /**
  4241. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4242. * Returns the updated Matrix.
  4243. */
  4244. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4245. if (index < 0 || index > 3) {
  4246. return this;
  4247. }
  4248. var i = index * 4;
  4249. this.m[i + 0] = x;
  4250. this.m[i + 1] = y;
  4251. this.m[i + 2] = z;
  4252. this.m[i + 3] = w;
  4253. this._markAsUpdated();
  4254. return this;
  4255. };
  4256. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4257. /**
  4258. * Static identity matrix to be used as readonly matrix
  4259. * Must not be updated.
  4260. */
  4261. get: function () {
  4262. return Matrix._identityReadOnly;
  4263. },
  4264. enumerable: true,
  4265. configurable: true
  4266. });
  4267. /**
  4268. * Returns a new Matrix set from the 16 passed floats.
  4269. */
  4270. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4271. var result = new Matrix();
  4272. result.m[0] = initialM11;
  4273. result.m[1] = initialM12;
  4274. result.m[2] = initialM13;
  4275. result.m[3] = initialM14;
  4276. result.m[4] = initialM21;
  4277. result.m[5] = initialM22;
  4278. result.m[6] = initialM23;
  4279. result.m[7] = initialM24;
  4280. result.m[8] = initialM31;
  4281. result.m[9] = initialM32;
  4282. result.m[10] = initialM33;
  4283. result.m[11] = initialM34;
  4284. result.m[12] = initialM41;
  4285. result.m[13] = initialM42;
  4286. result.m[14] = initialM43;
  4287. result.m[15] = initialM44;
  4288. return result;
  4289. };
  4290. /**
  4291. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4292. */
  4293. Matrix.Compose = function (scale, rotation, translation) {
  4294. var result = Matrix.Identity();
  4295. Matrix.ComposeToRef(scale, rotation, translation, result);
  4296. return result;
  4297. };
  4298. /**
  4299. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4300. */
  4301. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4302. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4303. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4304. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4305. result.setTranslation(translation);
  4306. };
  4307. /**
  4308. * Returns a new indentity Matrix.
  4309. */
  4310. Matrix.Identity = function () {
  4311. 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);
  4312. };
  4313. /**
  4314. * Sets the passed "result" as an identity matrix.
  4315. */
  4316. Matrix.IdentityToRef = function (result) {
  4317. 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);
  4318. };
  4319. /**
  4320. * Returns a new zero Matrix.
  4321. */
  4322. Matrix.Zero = function () {
  4323. 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);
  4324. };
  4325. /**
  4326. * Returns a new rotation matrix for "angle" radians around the X axis.
  4327. */
  4328. Matrix.RotationX = function (angle) {
  4329. var result = new Matrix();
  4330. Matrix.RotationXToRef(angle, result);
  4331. return result;
  4332. };
  4333. /**
  4334. * Returns a new Matrix as the passed inverted one.
  4335. */
  4336. Matrix.Invert = function (source) {
  4337. var result = new Matrix();
  4338. source.invertToRef(result);
  4339. return result;
  4340. };
  4341. /**
  4342. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4343. */
  4344. Matrix.RotationXToRef = function (angle, result) {
  4345. var s = Math.sin(angle);
  4346. var c = Math.cos(angle);
  4347. result.m[0] = 1.0;
  4348. result.m[15] = 1.0;
  4349. result.m[5] = c;
  4350. result.m[10] = c;
  4351. result.m[9] = -s;
  4352. result.m[6] = s;
  4353. result.m[1] = 0.0;
  4354. result.m[2] = 0.0;
  4355. result.m[3] = 0.0;
  4356. result.m[4] = 0.0;
  4357. result.m[7] = 0.0;
  4358. result.m[8] = 0.0;
  4359. result.m[11] = 0.0;
  4360. result.m[12] = 0.0;
  4361. result.m[13] = 0.0;
  4362. result.m[14] = 0.0;
  4363. result._markAsUpdated();
  4364. };
  4365. /**
  4366. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4367. */
  4368. Matrix.RotationY = function (angle) {
  4369. var result = new Matrix();
  4370. Matrix.RotationYToRef(angle, result);
  4371. return result;
  4372. };
  4373. /**
  4374. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4375. */
  4376. Matrix.RotationYToRef = function (angle, result) {
  4377. var s = Math.sin(angle);
  4378. var c = Math.cos(angle);
  4379. result.m[5] = 1.0;
  4380. result.m[15] = 1.0;
  4381. result.m[0] = c;
  4382. result.m[2] = -s;
  4383. result.m[8] = s;
  4384. result.m[10] = c;
  4385. result.m[1] = 0.0;
  4386. result.m[3] = 0.0;
  4387. result.m[4] = 0.0;
  4388. result.m[6] = 0.0;
  4389. result.m[7] = 0.0;
  4390. result.m[9] = 0.0;
  4391. result.m[11] = 0.0;
  4392. result.m[12] = 0.0;
  4393. result.m[13] = 0.0;
  4394. result.m[14] = 0.0;
  4395. result._markAsUpdated();
  4396. };
  4397. /**
  4398. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4399. */
  4400. Matrix.RotationZ = function (angle) {
  4401. var result = new Matrix();
  4402. Matrix.RotationZToRef(angle, result);
  4403. return result;
  4404. };
  4405. /**
  4406. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4407. */
  4408. Matrix.RotationZToRef = function (angle, result) {
  4409. var s = Math.sin(angle);
  4410. var c = Math.cos(angle);
  4411. result.m[10] = 1.0;
  4412. result.m[15] = 1.0;
  4413. result.m[0] = c;
  4414. result.m[1] = s;
  4415. result.m[4] = -s;
  4416. result.m[5] = c;
  4417. result.m[2] = 0.0;
  4418. result.m[3] = 0.0;
  4419. result.m[6] = 0.0;
  4420. result.m[7] = 0.0;
  4421. result.m[8] = 0.0;
  4422. result.m[9] = 0.0;
  4423. result.m[11] = 0.0;
  4424. result.m[12] = 0.0;
  4425. result.m[13] = 0.0;
  4426. result.m[14] = 0.0;
  4427. result._markAsUpdated();
  4428. };
  4429. /**
  4430. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4431. */
  4432. Matrix.RotationAxis = function (axis, angle) {
  4433. var result = Matrix.Zero();
  4434. Matrix.RotationAxisToRef(axis, angle, result);
  4435. return result;
  4436. };
  4437. /**
  4438. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4439. */
  4440. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4441. var s = Math.sin(-angle);
  4442. var c = Math.cos(-angle);
  4443. var c1 = 1 - c;
  4444. axis.normalize();
  4445. result.m[0] = (axis.x * axis.x) * c1 + c;
  4446. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4447. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4448. result.m[3] = 0.0;
  4449. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4450. result.m[5] = (axis.y * axis.y) * c1 + c;
  4451. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4452. result.m[7] = 0.0;
  4453. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4454. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4455. result.m[10] = (axis.z * axis.z) * c1 + c;
  4456. result.m[11] = 0.0;
  4457. result.m[15] = 1.0;
  4458. result._markAsUpdated();
  4459. };
  4460. /**
  4461. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4462. */
  4463. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4464. var result = new Matrix();
  4465. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4466. return result;
  4467. };
  4468. /**
  4469. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4470. */
  4471. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4472. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4473. this._tempQuaternion.toRotationMatrix(result);
  4474. };
  4475. /**
  4476. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4477. */
  4478. Matrix.Scaling = function (x, y, z) {
  4479. var result = Matrix.Zero();
  4480. Matrix.ScalingToRef(x, y, z, result);
  4481. return result;
  4482. };
  4483. /**
  4484. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4485. */
  4486. Matrix.ScalingToRef = function (x, y, z, result) {
  4487. result.m[0] = x;
  4488. result.m[1] = 0.0;
  4489. result.m[2] = 0.0;
  4490. result.m[3] = 0.0;
  4491. result.m[4] = 0.0;
  4492. result.m[5] = y;
  4493. result.m[6] = 0.0;
  4494. result.m[7] = 0.0;
  4495. result.m[8] = 0.0;
  4496. result.m[9] = 0.0;
  4497. result.m[10] = z;
  4498. result.m[11] = 0.0;
  4499. result.m[12] = 0.0;
  4500. result.m[13] = 0.0;
  4501. result.m[14] = 0.0;
  4502. result.m[15] = 1.0;
  4503. result._markAsUpdated();
  4504. };
  4505. /**
  4506. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4507. */
  4508. Matrix.Translation = function (x, y, z) {
  4509. var result = Matrix.Identity();
  4510. Matrix.TranslationToRef(x, y, z, result);
  4511. return result;
  4512. };
  4513. /**
  4514. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4515. */
  4516. Matrix.TranslationToRef = function (x, y, z, result) {
  4517. 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);
  4518. };
  4519. /**
  4520. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4521. */
  4522. Matrix.Lerp = function (startValue, endValue, gradient) {
  4523. var result = Matrix.Zero();
  4524. for (var index = 0; index < 16; index++) {
  4525. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4526. }
  4527. result._markAsUpdated();
  4528. return result;
  4529. };
  4530. /**
  4531. * Returns a new Matrix whose values are computed by :
  4532. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4533. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4534. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4535. */
  4536. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4537. var startScale = new Vector3(0, 0, 0);
  4538. var startRotation = new Quaternion();
  4539. var startTranslation = new Vector3(0, 0, 0);
  4540. startValue.decompose(startScale, startRotation, startTranslation);
  4541. var endScale = new Vector3(0, 0, 0);
  4542. var endRotation = new Quaternion();
  4543. var endTranslation = new Vector3(0, 0, 0);
  4544. endValue.decompose(endScale, endRotation, endTranslation);
  4545. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4546. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4547. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4548. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4549. };
  4550. /**
  4551. * 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".
  4552. * This methods works for a Left-Handed system.
  4553. */
  4554. Matrix.LookAtLH = function (eye, target, up) {
  4555. var result = Matrix.Zero();
  4556. Matrix.LookAtLHToRef(eye, target, up, result);
  4557. return result;
  4558. };
  4559. /**
  4560. * 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".
  4561. * This methods works for a Left-Handed system.
  4562. */
  4563. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4564. // Z axis
  4565. target.subtractToRef(eye, this._zAxis);
  4566. this._zAxis.normalize();
  4567. // X axis
  4568. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4569. if (this._xAxis.lengthSquared() === 0) {
  4570. this._xAxis.x = 1.0;
  4571. }
  4572. else {
  4573. this._xAxis.normalize();
  4574. }
  4575. // Y axis
  4576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4577. this._yAxis.normalize();
  4578. // Eye angles
  4579. var ex = -Vector3.Dot(this._xAxis, eye);
  4580. var ey = -Vector3.Dot(this._yAxis, eye);
  4581. var ez = -Vector3.Dot(this._zAxis, eye);
  4582. 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);
  4583. };
  4584. /**
  4585. * 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".
  4586. * This methods works for a Right-Handed system.
  4587. */
  4588. Matrix.LookAtRH = function (eye, target, up) {
  4589. var result = Matrix.Zero();
  4590. Matrix.LookAtRHToRef(eye, target, up, result);
  4591. return result;
  4592. };
  4593. /**
  4594. * 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".
  4595. * This methods works for a Left-Handed system.
  4596. */
  4597. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4598. // Z axis
  4599. eye.subtractToRef(target, this._zAxis);
  4600. this._zAxis.normalize();
  4601. // X axis
  4602. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4603. if (this._xAxis.lengthSquared() === 0) {
  4604. this._xAxis.x = 1.0;
  4605. }
  4606. else {
  4607. this._xAxis.normalize();
  4608. }
  4609. // Y axis
  4610. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4611. this._yAxis.normalize();
  4612. // Eye angles
  4613. var ex = -Vector3.Dot(this._xAxis, eye);
  4614. var ey = -Vector3.Dot(this._yAxis, eye);
  4615. var ez = -Vector3.Dot(this._zAxis, eye);
  4616. 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);
  4617. };
  4618. /**
  4619. * 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.
  4620. */
  4621. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4622. var matrix = Matrix.Zero();
  4623. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4624. return matrix;
  4625. };
  4626. /**
  4627. * 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.
  4628. */
  4629. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4630. var n = znear;
  4631. var f = zfar;
  4632. var a = 2.0 / width;
  4633. var b = 2.0 / height;
  4634. var c = 2.0 / (f - n);
  4635. var d = -(f + n) / (f - n);
  4636. 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);
  4637. };
  4638. /**
  4639. * 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.
  4640. */
  4641. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4642. var matrix = Matrix.Zero();
  4643. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4644. return matrix;
  4645. };
  4646. /**
  4647. * 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.
  4648. */
  4649. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4650. var n = znear;
  4651. var f = zfar;
  4652. var a = 2.0 / (right - left);
  4653. var b = 2.0 / (top - bottom);
  4654. var c = 2.0 / (f - n);
  4655. var d = -(f + n) / (f - n);
  4656. var i0 = (left + right) / (left - right);
  4657. var i1 = (top + bottom) / (bottom - top);
  4658. 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);
  4659. };
  4660. /**
  4661. * 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.
  4662. */
  4663. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4664. var matrix = Matrix.Zero();
  4665. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4666. return matrix;
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4672. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4673. result.m[10] *= -1.0;
  4674. };
  4675. /**
  4676. * 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.
  4677. */
  4678. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4679. var matrix = Matrix.Zero();
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 * n / width;
  4683. var b = 2.0 * n / height;
  4684. var c = (f + n) / (f - n);
  4685. var d = -2.0 * f * n / (f - n);
  4686. 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);
  4687. return matrix;
  4688. };
  4689. /**
  4690. * 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.
  4691. */
  4692. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4693. var matrix = Matrix.Zero();
  4694. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4695. return matrix;
  4696. };
  4697. /**
  4698. * 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.
  4699. */
  4700. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4701. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4702. var n = znear;
  4703. var f = zfar;
  4704. var t = 1.0 / (Math.tan(fov * 0.5));
  4705. var a = isVerticalFovFixed ? (t / aspect) : t;
  4706. var b = isVerticalFovFixed ? t : (t * aspect);
  4707. var c = (f + n) / (f - n);
  4708. var d = -2.0 * f * n / (f - n);
  4709. 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);
  4710. };
  4711. /**
  4712. * 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.
  4713. */
  4714. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4715. var matrix = Matrix.Zero();
  4716. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4717. return matrix;
  4718. };
  4719. /**
  4720. * 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.
  4721. */
  4722. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4723. //alternatively this could be expressed as:
  4724. // m = PerspectiveFovLHToRef
  4725. // m[10] *= -1.0;
  4726. // m[11] *= -1.0;
  4727. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4728. var n = znear;
  4729. var f = zfar;
  4730. var t = 1.0 / (Math.tan(fov * 0.5));
  4731. var a = isVerticalFovFixed ? (t / aspect) : t;
  4732. var b = isVerticalFovFixed ? t : (t * aspect);
  4733. var c = -(f + n) / (f - n);
  4734. var d = -2 * f * n / (f - n);
  4735. 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);
  4736. };
  4737. /**
  4738. * 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.
  4739. */
  4740. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4741. if (rightHanded === void 0) { rightHanded = false; }
  4742. var rightHandedFactor = rightHanded ? -1 : 1;
  4743. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4744. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4745. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4746. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4747. var xScale = 2.0 / (leftTan + rightTan);
  4748. var yScale = 2.0 / (upTan + downTan);
  4749. result.m[0] = xScale;
  4750. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4751. result.m[5] = yScale;
  4752. result.m[6] = result.m[7] = 0.0;
  4753. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4754. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4755. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4756. result.m[10] = -zfar / (znear - zfar);
  4757. result.m[11] = 1.0 * rightHandedFactor;
  4758. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4759. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4760. // result.m[14] = (znear * zfar) / (znear - zfar);
  4761. result._markAsUpdated();
  4762. };
  4763. /**
  4764. * Returns the final transformation matrix : world * view * projection * viewport
  4765. */
  4766. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4767. var cw = viewport.width;
  4768. var ch = viewport.height;
  4769. var cx = viewport.x;
  4770. var cy = viewport.y;
  4771. 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);
  4772. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4773. };
  4774. /**
  4775. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4776. */
  4777. Matrix.GetAsMatrix2x2 = function (matrix) {
  4778. return new Float32Array([
  4779. matrix.m[0], matrix.m[1],
  4780. matrix.m[4], matrix.m[5]
  4781. ]);
  4782. };
  4783. /**
  4784. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4785. */
  4786. Matrix.GetAsMatrix3x3 = function (matrix) {
  4787. return new Float32Array([
  4788. matrix.m[0], matrix.m[1], matrix.m[2],
  4789. matrix.m[4], matrix.m[5], matrix.m[6],
  4790. matrix.m[8], matrix.m[9], matrix.m[10]
  4791. ]);
  4792. };
  4793. /**
  4794. * Compute the transpose of the passed Matrix.
  4795. * Returns a new Matrix.
  4796. */
  4797. Matrix.Transpose = function (matrix) {
  4798. var result = new Matrix();
  4799. Matrix.TransposeToRef(matrix, result);
  4800. return result;
  4801. };
  4802. /**
  4803. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4804. */
  4805. Matrix.TransposeToRef = function (matrix, result) {
  4806. result.m[0] = matrix.m[0];
  4807. result.m[1] = matrix.m[4];
  4808. result.m[2] = matrix.m[8];
  4809. result.m[3] = matrix.m[12];
  4810. result.m[4] = matrix.m[1];
  4811. result.m[5] = matrix.m[5];
  4812. result.m[6] = matrix.m[9];
  4813. result.m[7] = matrix.m[13];
  4814. result.m[8] = matrix.m[2];
  4815. result.m[9] = matrix.m[6];
  4816. result.m[10] = matrix.m[10];
  4817. result.m[11] = matrix.m[14];
  4818. result.m[12] = matrix.m[3];
  4819. result.m[13] = matrix.m[7];
  4820. result.m[14] = matrix.m[11];
  4821. result.m[15] = matrix.m[15];
  4822. };
  4823. /**
  4824. * Returns a new Matrix as the reflection matrix across the passed plane.
  4825. */
  4826. Matrix.Reflection = function (plane) {
  4827. var matrix = new Matrix();
  4828. Matrix.ReflectionToRef(plane, matrix);
  4829. return matrix;
  4830. };
  4831. /**
  4832. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4833. */
  4834. Matrix.ReflectionToRef = function (plane, result) {
  4835. plane.normalize();
  4836. var x = plane.normal.x;
  4837. var y = plane.normal.y;
  4838. var z = plane.normal.z;
  4839. var temp = -2 * x;
  4840. var temp2 = -2 * y;
  4841. var temp3 = -2 * z;
  4842. result.m[0] = (temp * x) + 1;
  4843. result.m[1] = temp2 * x;
  4844. result.m[2] = temp3 * x;
  4845. result.m[3] = 0.0;
  4846. result.m[4] = temp * y;
  4847. result.m[5] = (temp2 * y) + 1;
  4848. result.m[6] = temp3 * y;
  4849. result.m[7] = 0.0;
  4850. result.m[8] = temp * z;
  4851. result.m[9] = temp2 * z;
  4852. result.m[10] = (temp3 * z) + 1;
  4853. result.m[11] = 0.0;
  4854. result.m[12] = temp * plane.d;
  4855. result.m[13] = temp2 * plane.d;
  4856. result.m[14] = temp3 * plane.d;
  4857. result.m[15] = 1.0;
  4858. result._markAsUpdated();
  4859. };
  4860. /**
  4861. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4862. */
  4863. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4864. result.m[0] = xaxis.x;
  4865. result.m[1] = xaxis.y;
  4866. result.m[2] = xaxis.z;
  4867. result.m[3] = 0.0;
  4868. result.m[4] = yaxis.x;
  4869. result.m[5] = yaxis.y;
  4870. result.m[6] = yaxis.z;
  4871. result.m[7] = 0.0;
  4872. result.m[8] = zaxis.x;
  4873. result.m[9] = zaxis.y;
  4874. result.m[10] = zaxis.z;
  4875. result.m[11] = 0.0;
  4876. result.m[12] = 0.0;
  4877. result.m[13] = 0.0;
  4878. result.m[14] = 0.0;
  4879. result.m[15] = 1.0;
  4880. result._markAsUpdated();
  4881. };
  4882. /**
  4883. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4884. */
  4885. Matrix.FromQuaternionToRef = function (quat, result) {
  4886. var xx = quat.x * quat.x;
  4887. var yy = quat.y * quat.y;
  4888. var zz = quat.z * quat.z;
  4889. var xy = quat.x * quat.y;
  4890. var zw = quat.z * quat.w;
  4891. var zx = quat.z * quat.x;
  4892. var yw = quat.y * quat.w;
  4893. var yz = quat.y * quat.z;
  4894. var xw = quat.x * quat.w;
  4895. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4896. result.m[1] = 2.0 * (xy + zw);
  4897. result.m[2] = 2.0 * (zx - yw);
  4898. result.m[3] = 0.0;
  4899. result.m[4] = 2.0 * (xy - zw);
  4900. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4901. result.m[6] = 2.0 * (yz + xw);
  4902. result.m[7] = 0.0;
  4903. result.m[8] = 2.0 * (zx + yw);
  4904. result.m[9] = 2.0 * (yz - xw);
  4905. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4906. result.m[11] = 0.0;
  4907. result.m[12] = 0.0;
  4908. result.m[13] = 0.0;
  4909. result.m[14] = 0.0;
  4910. result.m[15] = 1.0;
  4911. result._markAsUpdated();
  4912. };
  4913. Matrix._tempQuaternion = new Quaternion();
  4914. Matrix._xAxis = Vector3.Zero();
  4915. Matrix._yAxis = Vector3.Zero();
  4916. Matrix._zAxis = Vector3.Zero();
  4917. Matrix._updateFlagSeed = 0;
  4918. Matrix._identityReadOnly = Matrix.Identity();
  4919. return Matrix;
  4920. }());
  4921. BABYLON.Matrix = Matrix;
  4922. var Plane = /** @class */ (function () {
  4923. /**
  4924. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4925. */
  4926. function Plane(a, b, c, d) {
  4927. this.normal = new Vector3(a, b, c);
  4928. this.d = d;
  4929. }
  4930. /**
  4931. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4932. */
  4933. Plane.prototype.asArray = function () {
  4934. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4935. };
  4936. // Methods
  4937. /**
  4938. * Returns a new plane copied from the current Plane.
  4939. */
  4940. Plane.prototype.clone = function () {
  4941. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4942. };
  4943. /**
  4944. * Returns the string "Plane".
  4945. */
  4946. Plane.prototype.getClassName = function () {
  4947. return "Plane";
  4948. };
  4949. /**
  4950. * Returns the Plane hash code.
  4951. */
  4952. Plane.prototype.getHashCode = function () {
  4953. var hash = this.normal.getHashCode();
  4954. hash = (hash * 397) ^ (this.d || 0);
  4955. return hash;
  4956. };
  4957. /**
  4958. * Normalize the current Plane in place.
  4959. * Returns the updated Plane.
  4960. */
  4961. Plane.prototype.normalize = function () {
  4962. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4963. var magnitude = 0.0;
  4964. if (norm !== 0) {
  4965. magnitude = 1.0 / norm;
  4966. }
  4967. this.normal.x *= magnitude;
  4968. this.normal.y *= magnitude;
  4969. this.normal.z *= magnitude;
  4970. this.d *= magnitude;
  4971. return this;
  4972. };
  4973. /**
  4974. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4975. */
  4976. Plane.prototype.transform = function (transformation) {
  4977. var transposedMatrix = Matrix.Transpose(transformation);
  4978. var x = this.normal.x;
  4979. var y = this.normal.y;
  4980. var z = this.normal.z;
  4981. var d = this.d;
  4982. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4983. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4984. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4985. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4986. return new Plane(normalX, normalY, normalZ, finalD);
  4987. };
  4988. /**
  4989. * Returns the dot product (float) of the point coordinates and the plane normal.
  4990. */
  4991. Plane.prototype.dotCoordinate = function (point) {
  4992. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4993. };
  4994. /**
  4995. * Updates the current Plane from the plane defined by the three passed points.
  4996. * Returns the updated Plane.
  4997. */
  4998. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4999. var x1 = point2.x - point1.x;
  5000. var y1 = point2.y - point1.y;
  5001. var z1 = point2.z - point1.z;
  5002. var x2 = point3.x - point1.x;
  5003. var y2 = point3.y - point1.y;
  5004. var z2 = point3.z - point1.z;
  5005. var yz = (y1 * z2) - (z1 * y2);
  5006. var xz = (z1 * x2) - (x1 * z2);
  5007. var xy = (x1 * y2) - (y1 * x2);
  5008. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5009. var invPyth;
  5010. if (pyth !== 0) {
  5011. invPyth = 1.0 / pyth;
  5012. }
  5013. else {
  5014. invPyth = 0.0;
  5015. }
  5016. this.normal.x = yz * invPyth;
  5017. this.normal.y = xz * invPyth;
  5018. this.normal.z = xy * invPyth;
  5019. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5020. return this;
  5021. };
  5022. /**
  5023. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5024. */
  5025. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5026. var dot = Vector3.Dot(this.normal, direction);
  5027. return (dot <= epsilon);
  5028. };
  5029. /**
  5030. * Returns the signed distance (float) from the passed point to the Plane.
  5031. */
  5032. Plane.prototype.signedDistanceTo = function (point) {
  5033. return Vector3.Dot(point, this.normal) + this.d;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Returns a new Plane from the passed array.
  5038. */
  5039. Plane.FromArray = function (array) {
  5040. return new Plane(array[0], array[1], array[2], array[3]);
  5041. };
  5042. /**
  5043. * Returns a new Plane defined by the three passed points.
  5044. */
  5045. Plane.FromPoints = function (point1, point2, point3) {
  5046. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5047. result.copyFromPoints(point1, point2, point3);
  5048. return result;
  5049. };
  5050. /**
  5051. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5052. * Note : the vector "normal" is updated because normalized.
  5053. */
  5054. Plane.FromPositionAndNormal = function (origin, normal) {
  5055. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5056. normal.normalize();
  5057. result.normal = normal;
  5058. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5059. return result;
  5060. };
  5061. /**
  5062. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5063. */
  5064. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5065. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5066. return Vector3.Dot(point, normal) + d;
  5067. };
  5068. return Plane;
  5069. }());
  5070. BABYLON.Plane = Plane;
  5071. var Viewport = /** @class */ (function () {
  5072. /**
  5073. * Creates a Viewport object located at (x, y) and sized (width, height).
  5074. */
  5075. function Viewport(x, y, width, height) {
  5076. this.x = x;
  5077. this.y = y;
  5078. this.width = width;
  5079. this.height = height;
  5080. }
  5081. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5082. if (renderWidthOrEngine.getRenderWidth) {
  5083. var engine = renderWidthOrEngine;
  5084. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5085. }
  5086. var renderWidth = renderWidthOrEngine;
  5087. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5088. };
  5089. /**
  5090. * Returns a new Viewport copied from the current one.
  5091. */
  5092. Viewport.prototype.clone = function () {
  5093. return new Viewport(this.x, this.y, this.width, this.height);
  5094. };
  5095. return Viewport;
  5096. }());
  5097. BABYLON.Viewport = Viewport;
  5098. var Frustum = /** @class */ (function () {
  5099. function Frustum() {
  5100. }
  5101. /**
  5102. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5103. */
  5104. Frustum.GetPlanes = function (transform) {
  5105. var frustumPlanes = [];
  5106. for (var index = 0; index < 6; index++) {
  5107. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5108. }
  5109. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5110. return frustumPlanes;
  5111. };
  5112. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5113. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5114. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5115. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5116. frustumPlane.d = transform.m[15] + transform.m[14];
  5117. frustumPlane.normalize();
  5118. };
  5119. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5120. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5121. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5122. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5123. frustumPlane.d = transform.m[15] - transform.m[14];
  5124. frustumPlane.normalize();
  5125. };
  5126. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5127. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5128. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5129. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5130. frustumPlane.d = transform.m[15] + transform.m[12];
  5131. frustumPlane.normalize();
  5132. };
  5133. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5134. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5135. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5136. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5137. frustumPlane.d = transform.m[15] - transform.m[12];
  5138. frustumPlane.normalize();
  5139. };
  5140. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5141. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5142. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5143. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5144. frustumPlane.d = transform.m[15] - transform.m[13];
  5145. frustumPlane.normalize();
  5146. };
  5147. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5148. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5149. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5150. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5151. frustumPlane.d = transform.m[15] + transform.m[13];
  5152. frustumPlane.normalize();
  5153. };
  5154. /**
  5155. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5156. */
  5157. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5158. // Near
  5159. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5160. // Far
  5161. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5162. // Left
  5163. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5164. // Right
  5165. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5166. // Top
  5167. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5168. // Bottom
  5169. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5170. };
  5171. return Frustum;
  5172. }());
  5173. BABYLON.Frustum = Frustum;
  5174. var Space;
  5175. (function (Space) {
  5176. Space[Space["LOCAL"] = 0] = "LOCAL";
  5177. Space[Space["WORLD"] = 1] = "WORLD";
  5178. Space[Space["BONE"] = 2] = "BONE";
  5179. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5180. var Axis = /** @class */ (function () {
  5181. function Axis() {
  5182. }
  5183. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5184. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5185. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5186. return Axis;
  5187. }());
  5188. BABYLON.Axis = Axis;
  5189. ;
  5190. var BezierCurve = /** @class */ (function () {
  5191. function BezierCurve() {
  5192. }
  5193. /**
  5194. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5195. */
  5196. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5197. // Extract X (which is equal to time here)
  5198. var f0 = 1 - 3 * x2 + 3 * x1;
  5199. var f1 = 3 * x2 - 6 * x1;
  5200. var f2 = 3 * x1;
  5201. var refinedT = t;
  5202. for (var i = 0; i < 5; i++) {
  5203. var refinedT2 = refinedT * refinedT;
  5204. var refinedT3 = refinedT2 * refinedT;
  5205. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5206. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5207. refinedT -= (x - t) * slope;
  5208. refinedT = Math.min(1, Math.max(0, refinedT));
  5209. }
  5210. // Resolve cubic bezier for the given x
  5211. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5212. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5213. Math.pow(refinedT, 3);
  5214. };
  5215. return BezierCurve;
  5216. }());
  5217. BABYLON.BezierCurve = BezierCurve;
  5218. var Orientation;
  5219. (function (Orientation) {
  5220. Orientation[Orientation["CW"] = 0] = "CW";
  5221. Orientation[Orientation["CCW"] = 1] = "CCW";
  5222. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5223. var Angle = /** @class */ (function () {
  5224. /**
  5225. * Creates an Angle object of "radians" radians (float).
  5226. */
  5227. function Angle(radians) {
  5228. var _this = this;
  5229. /**
  5230. * Returns the Angle value in degrees (float).
  5231. */
  5232. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5233. /**
  5234. * Returns the Angle value in radians (float).
  5235. */
  5236. this.radians = function () { return _this._radians; };
  5237. this._radians = radians;
  5238. if (this._radians < 0.0)
  5239. this._radians += (2.0 * Math.PI);
  5240. }
  5241. /**
  5242. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5243. */
  5244. Angle.BetweenTwoPoints = function (a, b) {
  5245. var delta = b.subtract(a);
  5246. var theta = Math.atan2(delta.y, delta.x);
  5247. return new Angle(theta);
  5248. };
  5249. /**
  5250. * Returns a new Angle object from the passed float in radians.
  5251. */
  5252. Angle.FromRadians = function (radians) {
  5253. return new Angle(radians);
  5254. };
  5255. /**
  5256. * Returns a new Angle object from the passed float in degrees.
  5257. */
  5258. Angle.FromDegrees = function (degrees) {
  5259. return new Angle(degrees * Math.PI / 180.0);
  5260. };
  5261. return Angle;
  5262. }());
  5263. BABYLON.Angle = Angle;
  5264. var Arc2 = /** @class */ (function () {
  5265. /**
  5266. * Creates an Arc object from the three passed points : start, middle and end.
  5267. */
  5268. function Arc2(startPoint, midPoint, endPoint) {
  5269. this.startPoint = startPoint;
  5270. this.midPoint = midPoint;
  5271. this.endPoint = endPoint;
  5272. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5273. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5274. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5275. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5276. 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);
  5277. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5278. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5279. var a1 = this.startAngle.degrees();
  5280. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5281. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5282. // angles correction
  5283. if (a2 - a1 > +180.0)
  5284. a2 -= 360.0;
  5285. if (a2 - a1 < -180.0)
  5286. a2 += 360.0;
  5287. if (a3 - a2 > +180.0)
  5288. a3 -= 360.0;
  5289. if (a3 - a2 < -180.0)
  5290. a3 += 360.0;
  5291. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5292. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5293. }
  5294. return Arc2;
  5295. }());
  5296. BABYLON.Arc2 = Arc2;
  5297. var Path2 = /** @class */ (function () {
  5298. /**
  5299. * Creates a Path2 object from the starting 2D coordinates x and y.
  5300. */
  5301. function Path2(x, y) {
  5302. this._points = new Array();
  5303. this._length = 0.0;
  5304. this.closed = false;
  5305. this._points.push(new Vector2(x, y));
  5306. }
  5307. /**
  5308. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5309. * Returns the updated Path2.
  5310. */
  5311. Path2.prototype.addLineTo = function (x, y) {
  5312. if (this.closed) {
  5313. //Tools.Error("cannot add lines to closed paths");
  5314. return this;
  5315. }
  5316. var newPoint = new Vector2(x, y);
  5317. var previousPoint = this._points[this._points.length - 1];
  5318. this._points.push(newPoint);
  5319. this._length += newPoint.subtract(previousPoint).length();
  5320. return this;
  5321. };
  5322. /**
  5323. * 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.
  5324. * Returns the updated Path2.
  5325. */
  5326. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5327. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5328. if (this.closed) {
  5329. //Tools.Error("cannot add arcs to closed paths");
  5330. return this;
  5331. }
  5332. var startPoint = this._points[this._points.length - 1];
  5333. var midPoint = new Vector2(midX, midY);
  5334. var endPoint = new Vector2(endX, endY);
  5335. var arc = new Arc2(startPoint, midPoint, endPoint);
  5336. var increment = arc.angle.radians() / numberOfSegments;
  5337. if (arc.orientation === Orientation.CW)
  5338. increment *= -1;
  5339. var currentAngle = arc.startAngle.radians() + increment;
  5340. for (var i = 0; i < numberOfSegments; i++) {
  5341. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5342. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5343. this.addLineTo(x, y);
  5344. currentAngle += increment;
  5345. }
  5346. return this;
  5347. };
  5348. /**
  5349. * Closes the Path2.
  5350. * Returns the Path2.
  5351. */
  5352. Path2.prototype.close = function () {
  5353. this.closed = true;
  5354. return this;
  5355. };
  5356. /**
  5357. * Returns the Path2 total length (float).
  5358. */
  5359. Path2.prototype.length = function () {
  5360. var result = this._length;
  5361. if (!this.closed) {
  5362. var lastPoint = this._points[this._points.length - 1];
  5363. var firstPoint = this._points[0];
  5364. result += (firstPoint.subtract(lastPoint).length());
  5365. }
  5366. return result;
  5367. };
  5368. /**
  5369. * Returns the Path2 internal array of points.
  5370. */
  5371. Path2.prototype.getPoints = function () {
  5372. return this._points;
  5373. };
  5374. /**
  5375. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5376. */
  5377. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5378. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5379. //Tools.Error("normalized length position should be between 0 and 1.");
  5380. return Vector2.Zero();
  5381. }
  5382. var lengthPosition = normalizedLengthPosition * this.length();
  5383. var previousOffset = 0;
  5384. for (var i = 0; i < this._points.length; i++) {
  5385. var j = (i + 1) % this._points.length;
  5386. var a = this._points[i];
  5387. var b = this._points[j];
  5388. var bToA = b.subtract(a);
  5389. var nextOffset = (bToA.length() + previousOffset);
  5390. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5391. var dir = bToA.normalize();
  5392. var localOffset = lengthPosition - previousOffset;
  5393. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5394. }
  5395. previousOffset = nextOffset;
  5396. }
  5397. //Tools.Error("internal error");
  5398. return Vector2.Zero();
  5399. };
  5400. /**
  5401. * Returns a new Path2 starting at the coordinates (x, y).
  5402. */
  5403. Path2.StartingAt = function (x, y) {
  5404. return new Path2(x, y);
  5405. };
  5406. return Path2;
  5407. }());
  5408. BABYLON.Path2 = Path2;
  5409. var Path3D = /** @class */ (function () {
  5410. /**
  5411. * new Path3D(path, normal, raw)
  5412. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5413. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5414. * path : an array of Vector3, the curve axis of the Path3D
  5415. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5416. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5417. */
  5418. function Path3D(path, firstNormal, raw) {
  5419. if (firstNormal === void 0) { firstNormal = null; }
  5420. this.path = path;
  5421. this._curve = new Array();
  5422. this._distances = new Array();
  5423. this._tangents = new Array();
  5424. this._normals = new Array();
  5425. this._binormals = new Array();
  5426. for (var p = 0; p < path.length; p++) {
  5427. this._curve[p] = path[p].clone(); // hard copy
  5428. }
  5429. this._raw = raw || false;
  5430. this._compute(firstNormal);
  5431. }
  5432. /**
  5433. * Returns the Path3D array of successive Vector3 designing its curve.
  5434. */
  5435. Path3D.prototype.getCurve = function () {
  5436. return this._curve;
  5437. };
  5438. /**
  5439. * Returns an array populated with tangent vectors on each Path3D curve point.
  5440. */
  5441. Path3D.prototype.getTangents = function () {
  5442. return this._tangents;
  5443. };
  5444. /**
  5445. * Returns an array populated with normal vectors on each Path3D curve point.
  5446. */
  5447. Path3D.prototype.getNormals = function () {
  5448. return this._normals;
  5449. };
  5450. /**
  5451. * Returns an array populated with binormal vectors on each Path3D curve point.
  5452. */
  5453. Path3D.prototype.getBinormals = function () {
  5454. return this._binormals;
  5455. };
  5456. /**
  5457. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5458. */
  5459. Path3D.prototype.getDistances = function () {
  5460. return this._distances;
  5461. };
  5462. /**
  5463. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5464. * Returns the same object updated.
  5465. */
  5466. Path3D.prototype.update = function (path, firstNormal) {
  5467. if (firstNormal === void 0) { firstNormal = null; }
  5468. for (var p = 0; p < path.length; p++) {
  5469. this._curve[p].x = path[p].x;
  5470. this._curve[p].y = path[p].y;
  5471. this._curve[p].z = path[p].z;
  5472. }
  5473. this._compute(firstNormal);
  5474. return this;
  5475. };
  5476. // private function compute() : computes tangents, normals and binormals
  5477. Path3D.prototype._compute = function (firstNormal) {
  5478. var l = this._curve.length;
  5479. // first and last tangents
  5480. this._tangents[0] = this._getFirstNonNullVector(0);
  5481. if (!this._raw) {
  5482. this._tangents[0].normalize();
  5483. }
  5484. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5485. if (!this._raw) {
  5486. this._tangents[l - 1].normalize();
  5487. }
  5488. // normals and binormals at first point : arbitrary vector with _normalVector()
  5489. var tg0 = this._tangents[0];
  5490. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5491. this._normals[0] = pp0;
  5492. if (!this._raw) {
  5493. this._normals[0].normalize();
  5494. }
  5495. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5496. if (!this._raw) {
  5497. this._binormals[0].normalize();
  5498. }
  5499. this._distances[0] = 0.0;
  5500. // normals and binormals : next points
  5501. var prev; // previous vector (segment)
  5502. var cur; // current vector (segment)
  5503. var curTang; // current tangent
  5504. // previous normal
  5505. var prevBinor; // previous binormal
  5506. for (var i = 1; i < l; i++) {
  5507. // tangents
  5508. prev = this._getLastNonNullVector(i);
  5509. if (i < l - 1) {
  5510. cur = this._getFirstNonNullVector(i);
  5511. this._tangents[i] = prev.add(cur);
  5512. this._tangents[i].normalize();
  5513. }
  5514. this._distances[i] = this._distances[i - 1] + prev.length();
  5515. // normals and binormals
  5516. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5517. curTang = this._tangents[i];
  5518. prevBinor = this._binormals[i - 1];
  5519. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5520. if (!this._raw) {
  5521. this._normals[i].normalize();
  5522. }
  5523. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5524. if (!this._raw) {
  5525. this._binormals[i].normalize();
  5526. }
  5527. }
  5528. };
  5529. // private function getFirstNonNullVector(index)
  5530. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5531. Path3D.prototype._getFirstNonNullVector = function (index) {
  5532. var i = 1;
  5533. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5534. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5535. i++;
  5536. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5537. }
  5538. return nNVector;
  5539. };
  5540. // private function getLastNonNullVector(index)
  5541. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5542. Path3D.prototype._getLastNonNullVector = function (index) {
  5543. var i = 1;
  5544. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5545. while (nLVector.length() === 0 && index > i + 1) {
  5546. i++;
  5547. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5548. }
  5549. return nLVector;
  5550. };
  5551. // private function normalVector(v0, vt, va) :
  5552. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5553. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5554. Path3D.prototype._normalVector = function (v0, vt, va) {
  5555. var normal0;
  5556. var tgl = vt.length();
  5557. if (tgl === 0.0) {
  5558. tgl = 1.0;
  5559. }
  5560. if (va === undefined || va === null) {
  5561. var point;
  5562. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5563. point = new Vector3(0.0, -1.0, 0.0);
  5564. }
  5565. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5566. point = new Vector3(1.0, 0.0, 0.0);
  5567. }
  5568. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5569. point = new Vector3(0.0, 0.0, 1.0);
  5570. }
  5571. else {
  5572. point = Vector3.Zero();
  5573. }
  5574. normal0 = Vector3.Cross(vt, point);
  5575. }
  5576. else {
  5577. normal0 = Vector3.Cross(vt, va);
  5578. Vector3.CrossToRef(normal0, vt, normal0);
  5579. }
  5580. normal0.normalize();
  5581. return normal0;
  5582. };
  5583. return Path3D;
  5584. }());
  5585. BABYLON.Path3D = Path3D;
  5586. var Curve3 = /** @class */ (function () {
  5587. /**
  5588. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5589. * A Curve3 is designed from a series of successive Vector3.
  5590. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5591. */
  5592. function Curve3(points) {
  5593. this._length = 0.0;
  5594. this._points = points;
  5595. this._length = this._computeLength(points);
  5596. }
  5597. /**
  5598. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5599. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5600. * @param v1 (Vector3) the control point
  5601. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5602. * @param nbPoints (integer) the wanted number of points in the curve
  5603. */
  5604. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5605. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5606. var bez = new Array();
  5607. var equation = function (t, val0, val1, val2) {
  5608. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5609. return res;
  5610. };
  5611. for (var i = 0; i <= nbPoints; i++) {
  5612. 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)));
  5613. }
  5614. return new Curve3(bez);
  5615. };
  5616. /**
  5617. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5618. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5619. * @param v1 (Vector3) the first control point
  5620. * @param v2 (Vector3) the second control point
  5621. * @param v3 (Vector3) the end point of the Cubic Bezier
  5622. * @param nbPoints (integer) the wanted number of points in the curve
  5623. */
  5624. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5625. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5626. var bez = new Array();
  5627. var equation = function (t, val0, val1, val2, val3) {
  5628. 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;
  5629. return res;
  5630. };
  5631. for (var i = 0; i <= nbPoints; i++) {
  5632. 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)));
  5633. }
  5634. return new Curve3(bez);
  5635. };
  5636. /**
  5637. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5638. * @param p1 (Vector3) the origin point of the Hermite Spline
  5639. * @param t1 (Vector3) the tangent vector at the origin point
  5640. * @param p2 (Vector3) the end point of the Hermite Spline
  5641. * @param t2 (Vector3) the tangent vector at the end point
  5642. * @param nbPoints (integer) the wanted number of points in the curve
  5643. */
  5644. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5645. var hermite = new Array();
  5646. var step = 1.0 / nbPoints;
  5647. for (var i = 0; i <= nbPoints; i++) {
  5648. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5649. }
  5650. return new Curve3(hermite);
  5651. };
  5652. /**
  5653. * Returns a Curve3 object along a CatmullRom Spline curve :
  5654. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5655. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5656. */
  5657. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5658. var totalPoints = new Array();
  5659. totalPoints.push(points[0].clone());
  5660. Array.prototype.push.apply(totalPoints, points);
  5661. totalPoints.push(points[points.length - 1].clone());
  5662. var catmullRom = new Array();
  5663. var step = 1.0 / nbPoints;
  5664. var amount = 0.0;
  5665. for (var i = 0; i < totalPoints.length - 3; i++) {
  5666. amount = 0;
  5667. for (var c = 0; c < nbPoints; c++) {
  5668. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5669. amount += step;
  5670. }
  5671. }
  5672. i--;
  5673. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5674. return new Curve3(catmullRom);
  5675. };
  5676. /**
  5677. * Returns the Curve3 stored array of successive Vector3
  5678. */
  5679. Curve3.prototype.getPoints = function () {
  5680. return this._points;
  5681. };
  5682. /**
  5683. * Returns the computed length (float) of the curve.
  5684. */
  5685. Curve3.prototype.length = function () {
  5686. return this._length;
  5687. };
  5688. /**
  5689. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5690. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5691. * curveA and curveB keep unchanged.
  5692. */
  5693. Curve3.prototype.continue = function (curve) {
  5694. var lastPoint = this._points[this._points.length - 1];
  5695. var continuedPoints = this._points.slice();
  5696. var curvePoints = curve.getPoints();
  5697. for (var i = 1; i < curvePoints.length; i++) {
  5698. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5699. }
  5700. var continuedCurve = new Curve3(continuedPoints);
  5701. return continuedCurve;
  5702. };
  5703. Curve3.prototype._computeLength = function (path) {
  5704. var l = 0;
  5705. for (var i = 1; i < path.length; i++) {
  5706. l += (path[i].subtract(path[i - 1])).length();
  5707. }
  5708. return l;
  5709. };
  5710. return Curve3;
  5711. }());
  5712. BABYLON.Curve3 = Curve3;
  5713. // Vertex formats
  5714. var PositionNormalVertex = /** @class */ (function () {
  5715. function PositionNormalVertex(position, normal) {
  5716. if (position === void 0) { position = Vector3.Zero(); }
  5717. if (normal === void 0) { normal = Vector3.Up(); }
  5718. this.position = position;
  5719. this.normal = normal;
  5720. }
  5721. PositionNormalVertex.prototype.clone = function () {
  5722. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5723. };
  5724. return PositionNormalVertex;
  5725. }());
  5726. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5727. var PositionNormalTextureVertex = /** @class */ (function () {
  5728. function PositionNormalTextureVertex(position, normal, uv) {
  5729. if (position === void 0) { position = Vector3.Zero(); }
  5730. if (normal === void 0) { normal = Vector3.Up(); }
  5731. if (uv === void 0) { uv = Vector2.Zero(); }
  5732. this.position = position;
  5733. this.normal = normal;
  5734. this.uv = uv;
  5735. }
  5736. PositionNormalTextureVertex.prototype.clone = function () {
  5737. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5738. };
  5739. return PositionNormalTextureVertex;
  5740. }());
  5741. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5742. // Temporary pre-allocated objects for engine internal use
  5743. // usage in any internal function :
  5744. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5745. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5746. var Tmp = /** @class */ (function () {
  5747. function Tmp() {
  5748. }
  5749. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5750. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5751. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5752. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5753. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5754. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5755. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5756. Matrix.Zero(), Matrix.Zero(),
  5757. Matrix.Zero(), Matrix.Zero(),
  5758. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5759. return Tmp;
  5760. }());
  5761. BABYLON.Tmp = Tmp;
  5762. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5763. var MathTmp = /** @class */ (function () {
  5764. function MathTmp() {
  5765. }
  5766. MathTmp.Vector3 = [Vector3.Zero()];
  5767. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5768. MathTmp.Quaternion = [Quaternion.Zero()];
  5769. return MathTmp;
  5770. }());
  5771. })(BABYLON || (BABYLON = {}));
  5772. //# sourceMappingURL=babylon.math.js.map
  5773. var BABYLON;
  5774. (function (BABYLON) {
  5775. var Scalar = /** @class */ (function () {
  5776. function Scalar() {
  5777. }
  5778. /**
  5779. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5780. */
  5781. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5782. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5783. var num = a - b;
  5784. return -epsilon <= num && num <= epsilon;
  5785. };
  5786. /**
  5787. * Returns a string : the upper case translation of the number i to hexadecimal.
  5788. */
  5789. Scalar.ToHex = function (i) {
  5790. var str = i.toString(16);
  5791. if (i <= 15) {
  5792. return ("0" + str).toUpperCase();
  5793. }
  5794. return str.toUpperCase();
  5795. };
  5796. /**
  5797. * Returns -1 if value is negative and +1 is value is positive.
  5798. * Returns the value itself if it's equal to zero.
  5799. */
  5800. Scalar.Sign = function (value) {
  5801. value = +value; // convert to a number
  5802. if (value === 0 || isNaN(value))
  5803. return value;
  5804. return value > 0 ? 1 : -1;
  5805. };
  5806. /**
  5807. * Returns the value itself if it's between min and max.
  5808. * Returns min if the value is lower than min.
  5809. * Returns max if the value is greater than max.
  5810. */
  5811. Scalar.Clamp = function (value, min, max) {
  5812. if (min === void 0) { min = 0; }
  5813. if (max === void 0) { max = 1; }
  5814. return Math.min(max, Math.max(min, value));
  5815. };
  5816. /**
  5817. * Returns the log2 of value.
  5818. */
  5819. Scalar.Log2 = function (value) {
  5820. return Math.log(value) * Math.LOG2E;
  5821. };
  5822. /**
  5823. * Loops the value, so that it is never larger than length and never smaller than 0.
  5824. *
  5825. * This is similar to the modulo operator but it works with floating point numbers.
  5826. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5827. * With t = 5 and length = 2.5, the result would be 0.0.
  5828. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5829. */
  5830. Scalar.Repeat = function (value, length) {
  5831. return value - Math.floor(value / length) * length;
  5832. };
  5833. /**
  5834. * Normalize the value between 0.0 and 1.0 using min and max values
  5835. */
  5836. Scalar.Normalize = function (value, min, max) {
  5837. return (value - min) / (max - min);
  5838. };
  5839. /**
  5840. * Denormalize the value from 0.0 and 1.0 using min and max values
  5841. */
  5842. Scalar.Denormalize = function (normalized, min, max) {
  5843. return (normalized * (max - min) + min);
  5844. };
  5845. /**
  5846. * Calculates the shortest difference between two given angles given in degrees.
  5847. */
  5848. Scalar.DeltaAngle = function (current, target) {
  5849. var num = Scalar.Repeat(target - current, 360.0);
  5850. if (num > 180.0) {
  5851. num -= 360.0;
  5852. }
  5853. return num;
  5854. };
  5855. /**
  5856. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5857. *
  5858. * The returned value will move back and forth between 0 and length
  5859. */
  5860. Scalar.PingPong = function (tx, length) {
  5861. var t = Scalar.Repeat(tx, length * 2.0);
  5862. return length - Math.abs(t - length);
  5863. };
  5864. /**
  5865. * Interpolates between min and max with smoothing at the limits.
  5866. *
  5867. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5868. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5869. */
  5870. Scalar.SmoothStep = function (from, to, tx) {
  5871. var t = Scalar.Clamp(tx);
  5872. t = -2.0 * t * t * t + 3.0 * t * t;
  5873. return to * t + from * (1.0 - t);
  5874. };
  5875. /**
  5876. * Moves a value current towards target.
  5877. *
  5878. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5879. * Negative values of maxDelta pushes the value away from target.
  5880. */
  5881. Scalar.MoveTowards = function (current, target, maxDelta) {
  5882. var result = 0;
  5883. if (Math.abs(target - current) <= maxDelta) {
  5884. result = target;
  5885. }
  5886. else {
  5887. result = current + Scalar.Sign(target - current) * maxDelta;
  5888. }
  5889. return result;
  5890. };
  5891. /**
  5892. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5893. *
  5894. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5895. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5896. */
  5897. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5898. var num = Scalar.DeltaAngle(current, target);
  5899. var result = 0;
  5900. if (-maxDelta < num && num < maxDelta) {
  5901. result = target;
  5902. }
  5903. else {
  5904. target = current + num;
  5905. result = Scalar.MoveTowards(current, target, maxDelta);
  5906. }
  5907. return result;
  5908. };
  5909. /**
  5910. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5911. */
  5912. Scalar.Lerp = function (start, end, amount) {
  5913. return start + ((end - start) * amount);
  5914. };
  5915. /**
  5916. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5917. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5918. */
  5919. Scalar.LerpAngle = function (start, end, amount) {
  5920. var num = Scalar.Repeat(end - start, 360.0);
  5921. if (num > 180.0) {
  5922. num -= 360.0;
  5923. }
  5924. return start + num * Scalar.Clamp(amount);
  5925. };
  5926. /**
  5927. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5928. */
  5929. Scalar.InverseLerp = function (a, b, value) {
  5930. var result = 0;
  5931. if (a != b) {
  5932. result = Scalar.Clamp((value - a) / (b - a));
  5933. }
  5934. else {
  5935. result = 0.0;
  5936. }
  5937. return result;
  5938. };
  5939. /**
  5940. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5941. */
  5942. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5943. var squared = amount * amount;
  5944. var cubed = amount * squared;
  5945. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5946. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5947. var part3 = (cubed - (2.0 * squared)) + amount;
  5948. var part4 = cubed - squared;
  5949. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5950. };
  5951. /**
  5952. * Returns a random float number between and min and max values
  5953. */
  5954. Scalar.RandomRange = function (min, max) {
  5955. if (min === max)
  5956. return min;
  5957. return ((Math.random() * (max - min)) + min);
  5958. };
  5959. /**
  5960. * This function returns percentage of a number in a given range.
  5961. *
  5962. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5963. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5964. */
  5965. Scalar.RangeToPercent = function (number, min, max) {
  5966. return ((number - min) / (max - min));
  5967. };
  5968. /**
  5969. * This function returns number that corresponds to the percentage in a given range.
  5970. *
  5971. * PercentToRange(0.34,0,100) will return 34.
  5972. */
  5973. Scalar.PercentToRange = function (percent, min, max) {
  5974. return ((max - min) * percent + min);
  5975. };
  5976. /**
  5977. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5978. * @param angle The angle to normalize in radian.
  5979. * @return The converted angle.
  5980. */
  5981. Scalar.NormalizeRadians = function (angle) {
  5982. // More precise but slower version kept for reference.
  5983. // angle = angle % Tools.TwoPi;
  5984. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5985. //if (angle > Math.PI) {
  5986. // angle -= Tools.TwoPi;
  5987. //}
  5988. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5989. return angle;
  5990. };
  5991. /**
  5992. * Two pi constants convenient for computation.
  5993. */
  5994. Scalar.TwoPi = Math.PI * 2;
  5995. return Scalar;
  5996. }());
  5997. BABYLON.Scalar = Scalar;
  5998. })(BABYLON || (BABYLON = {}));
  5999. //# sourceMappingURL=babylon.math.scalar.js.map
  6000. //# sourceMappingURL=babylon.mixins.js.map
  6001. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6002. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6003. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6004. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6005. //# sourceMappingURL=babylon.webgl2.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var __decoratorInitialStore = {};
  6009. var __mergedStore = {};
  6010. var _copySource = function (creationFunction, source, instanciate) {
  6011. var destination = creationFunction();
  6012. // Tags
  6013. if (BABYLON.Tags) {
  6014. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6015. }
  6016. var classStore = getMergedStore(destination);
  6017. // Properties
  6018. for (var property in classStore) {
  6019. var propertyDescriptor = classStore[property];
  6020. var sourceProperty = source[property];
  6021. var propertyType = propertyDescriptor.type;
  6022. if (sourceProperty !== undefined && sourceProperty !== null) {
  6023. switch (propertyType) {
  6024. case 0: // Value
  6025. case 6:// Mesh reference
  6026. destination[property] = sourceProperty;
  6027. break;
  6028. case 1:// Texture
  6029. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6030. break;
  6031. case 2: // Color3
  6032. case 3: // FresnelParameters
  6033. case 4: // Vector2
  6034. case 5: // Vector3
  6035. case 7: // Color Curves
  6036. case 10:// Quaternion
  6037. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. return destination;
  6043. };
  6044. function getDirectStore(target) {
  6045. var classKey = target.getClassName();
  6046. if (!__decoratorInitialStore[classKey]) {
  6047. __decoratorInitialStore[classKey] = {};
  6048. }
  6049. return __decoratorInitialStore[classKey];
  6050. }
  6051. /**
  6052. * Return the list of properties flagged as serializable
  6053. * @param target: host object
  6054. */
  6055. function getMergedStore(target) {
  6056. var classKey = target.getClassName();
  6057. if (__mergedStore[classKey]) {
  6058. return __mergedStore[classKey];
  6059. }
  6060. __mergedStore[classKey] = {};
  6061. var store = __mergedStore[classKey];
  6062. var currentTarget = target;
  6063. var currentKey = classKey;
  6064. while (currentKey) {
  6065. var initialStore = __decoratorInitialStore[currentKey];
  6066. for (var property in initialStore) {
  6067. store[property] = initialStore[property];
  6068. }
  6069. var parent_1 = void 0;
  6070. var done = false;
  6071. do {
  6072. parent_1 = Object.getPrototypeOf(currentTarget);
  6073. if (!parent_1.getClassName) {
  6074. done = true;
  6075. break;
  6076. }
  6077. if (parent_1.getClassName() !== currentKey) {
  6078. break;
  6079. }
  6080. currentTarget = parent_1;
  6081. } while (parent_1);
  6082. if (done) {
  6083. break;
  6084. }
  6085. currentKey = parent_1.getClassName();
  6086. currentTarget = parent_1;
  6087. }
  6088. return store;
  6089. }
  6090. function generateSerializableMember(type, sourceName) {
  6091. return function (target, propertyKey) {
  6092. var classStore = getDirectStore(target);
  6093. if (!classStore[propertyKey]) {
  6094. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6095. }
  6096. };
  6097. }
  6098. function generateExpandMember(setCallback, targetKey) {
  6099. if (targetKey === void 0) { targetKey = null; }
  6100. return function (target, propertyKey) {
  6101. var key = targetKey || ("_" + propertyKey);
  6102. Object.defineProperty(target, propertyKey, {
  6103. get: function () {
  6104. return this[key];
  6105. },
  6106. set: function (value) {
  6107. if (this[key] === value) {
  6108. return;
  6109. }
  6110. this[key] = value;
  6111. target[setCallback].apply(this);
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. };
  6117. }
  6118. function expandToProperty(callback, targetKey) {
  6119. if (targetKey === void 0) { targetKey = null; }
  6120. return generateExpandMember(callback, targetKey);
  6121. }
  6122. BABYLON.expandToProperty = expandToProperty;
  6123. function serialize(sourceName) {
  6124. return generateSerializableMember(0, sourceName); // value member
  6125. }
  6126. BABYLON.serialize = serialize;
  6127. function serializeAsTexture(sourceName) {
  6128. return generateSerializableMember(1, sourceName); // texture member
  6129. }
  6130. BABYLON.serializeAsTexture = serializeAsTexture;
  6131. function serializeAsColor3(sourceName) {
  6132. return generateSerializableMember(2, sourceName); // color3 member
  6133. }
  6134. BABYLON.serializeAsColor3 = serializeAsColor3;
  6135. function serializeAsFresnelParameters(sourceName) {
  6136. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6137. }
  6138. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6139. function serializeAsVector2(sourceName) {
  6140. return generateSerializableMember(4, sourceName); // vector2 member
  6141. }
  6142. BABYLON.serializeAsVector2 = serializeAsVector2;
  6143. function serializeAsVector3(sourceName) {
  6144. return generateSerializableMember(5, sourceName); // vector3 member
  6145. }
  6146. BABYLON.serializeAsVector3 = serializeAsVector3;
  6147. function serializeAsMeshReference(sourceName) {
  6148. return generateSerializableMember(6, sourceName); // mesh reference member
  6149. }
  6150. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6151. function serializeAsColorCurves(sourceName) {
  6152. return generateSerializableMember(7, sourceName); // color curves
  6153. }
  6154. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6155. function serializeAsColor4(sourceName) {
  6156. return generateSerializableMember(8, sourceName); // color 4
  6157. }
  6158. BABYLON.serializeAsColor4 = serializeAsColor4;
  6159. function serializeAsImageProcessingConfiguration(sourceName) {
  6160. return generateSerializableMember(9, sourceName); // image processing
  6161. }
  6162. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6163. function serializeAsQuaternion(sourceName) {
  6164. return generateSerializableMember(10, sourceName); // quaternion member
  6165. }
  6166. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6167. var SerializationHelper = /** @class */ (function () {
  6168. function SerializationHelper() {
  6169. }
  6170. SerializationHelper.Serialize = function (entity, serializationObject) {
  6171. if (!serializationObject) {
  6172. serializationObject = {};
  6173. }
  6174. // Tags
  6175. if (BABYLON.Tags) {
  6176. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6177. }
  6178. var serializedProperties = getMergedStore(entity);
  6179. // Properties
  6180. for (var property in serializedProperties) {
  6181. var propertyDescriptor = serializedProperties[property];
  6182. var targetPropertyName = propertyDescriptor.sourceName || property;
  6183. var propertyType = propertyDescriptor.type;
  6184. var sourceProperty = entity[property];
  6185. if (sourceProperty !== undefined && sourceProperty !== null) {
  6186. switch (propertyType) {
  6187. case 0:// Value
  6188. serializationObject[targetPropertyName] = sourceProperty;
  6189. break;
  6190. case 1:// Texture
  6191. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6192. break;
  6193. case 2:// Color3
  6194. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6195. break;
  6196. case 3:// FresnelParameters
  6197. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6198. break;
  6199. case 4:// Vector2
  6200. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6201. break;
  6202. case 5:// Vector3
  6203. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6204. break;
  6205. case 6:// Mesh reference
  6206. serializationObject[targetPropertyName] = sourceProperty.id;
  6207. break;
  6208. case 7:// Color Curves
  6209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6210. break;
  6211. case 8:// Color 4
  6212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6213. break;
  6214. case 9:// Image Processing
  6215. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6216. break;
  6217. }
  6218. }
  6219. }
  6220. return serializationObject;
  6221. };
  6222. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6223. if (rootUrl === void 0) { rootUrl = null; }
  6224. var destination = creationFunction();
  6225. if (!rootUrl) {
  6226. rootUrl = "";
  6227. }
  6228. // Tags
  6229. if (BABYLON.Tags) {
  6230. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6231. }
  6232. var classStore = getMergedStore(destination);
  6233. // Properties
  6234. for (var property in classStore) {
  6235. var propertyDescriptor = classStore[property];
  6236. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6237. var propertyType = propertyDescriptor.type;
  6238. if (sourceProperty !== undefined && sourceProperty !== null) {
  6239. var dest = destination;
  6240. switch (propertyType) {
  6241. case 0:// Value
  6242. dest[property] = sourceProperty;
  6243. break;
  6244. case 1:// Texture
  6245. if (scene) {
  6246. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6247. }
  6248. break;
  6249. case 2:// Color3
  6250. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6251. break;
  6252. case 3:// FresnelParameters
  6253. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6254. break;
  6255. case 4:// Vector2
  6256. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6257. break;
  6258. case 5:// Vector3
  6259. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6260. break;
  6261. case 6:// Mesh reference
  6262. if (scene) {
  6263. dest[property] = scene.getLastMeshByID(sourceProperty);
  6264. }
  6265. break;
  6266. case 7:// Color Curves
  6267. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6268. break;
  6269. case 8:// Color 4
  6270. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6271. break;
  6272. case 9:// Image Processing
  6273. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6274. break;
  6275. }
  6276. }
  6277. }
  6278. return destination;
  6279. };
  6280. SerializationHelper.Clone = function (creationFunction, source) {
  6281. return _copySource(creationFunction, source, false);
  6282. };
  6283. SerializationHelper.Instanciate = function (creationFunction, source) {
  6284. return _copySource(creationFunction, source, true);
  6285. };
  6286. return SerializationHelper;
  6287. }());
  6288. BABYLON.SerializationHelper = SerializationHelper;
  6289. })(BABYLON || (BABYLON = {}));
  6290. //# sourceMappingURL=babylon.decorators.js.map
  6291. var BABYLON;
  6292. (function (BABYLON) {
  6293. /**
  6294. * A class serves as a medium between the observable and its observers
  6295. */
  6296. var EventState = /** @class */ (function () {
  6297. /**
  6298. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6299. */
  6300. function EventState(mask, skipNextObservers, target, currentTarget) {
  6301. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6302. this.initalize(mask, skipNextObservers, target, currentTarget);
  6303. }
  6304. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6305. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6306. this.mask = mask;
  6307. this.skipNextObservers = skipNextObservers;
  6308. this.target = target;
  6309. this.currentTarget = currentTarget;
  6310. return this;
  6311. };
  6312. return EventState;
  6313. }());
  6314. BABYLON.EventState = EventState;
  6315. /**
  6316. * Represent an Observer registered to a given Observable object.
  6317. */
  6318. var Observer = /** @class */ (function () {
  6319. function Observer(callback, mask, scope) {
  6320. if (scope === void 0) { scope = null; }
  6321. this.callback = callback;
  6322. this.mask = mask;
  6323. this.scope = scope;
  6324. }
  6325. return Observer;
  6326. }());
  6327. BABYLON.Observer = Observer;
  6328. /**
  6329. * Represent a list of observers registered to multiple Observables object.
  6330. */
  6331. var MultiObserver = /** @class */ (function () {
  6332. function MultiObserver() {
  6333. }
  6334. MultiObserver.prototype.dispose = function () {
  6335. if (this._observers && this._observables) {
  6336. for (var index = 0; index < this._observers.length; index++) {
  6337. this._observables[index].remove(this._observers[index]);
  6338. }
  6339. }
  6340. this._observers = null;
  6341. this._observables = null;
  6342. };
  6343. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6344. if (mask === void 0) { mask = -1; }
  6345. if (scope === void 0) { scope = null; }
  6346. var result = new MultiObserver();
  6347. result._observers = new Array();
  6348. result._observables = observables;
  6349. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6350. var observable = observables_1[_i];
  6351. var observer = observable.add(callback, mask, false, scope);
  6352. if (observer) {
  6353. result._observers.push(observer);
  6354. }
  6355. }
  6356. return result;
  6357. };
  6358. return MultiObserver;
  6359. }());
  6360. BABYLON.MultiObserver = MultiObserver;
  6361. /**
  6362. * The Observable class is a simple implementation of the Observable pattern.
  6363. * 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.
  6364. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6365. * 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).
  6366. * 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.
  6367. */
  6368. var Observable = /** @class */ (function () {
  6369. function Observable(onObserverAdded) {
  6370. this._observers = new Array();
  6371. this._eventState = new EventState(0);
  6372. if (onObserverAdded) {
  6373. this._onObserverAdded = onObserverAdded;
  6374. }
  6375. }
  6376. /**
  6377. * Create a new Observer with the specified callback
  6378. * @param callback the callback that will be executed for that Observer
  6379. * @param mask the mask used to filter observers
  6380. * @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.
  6381. * @param scope optional scope for the callback to be called from
  6382. */
  6383. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6384. if (mask === void 0) { mask = -1; }
  6385. if (insertFirst === void 0) { insertFirst = false; }
  6386. if (scope === void 0) { scope = null; }
  6387. if (!callback) {
  6388. return null;
  6389. }
  6390. var observer = new Observer(callback, mask, scope);
  6391. if (insertFirst) {
  6392. this._observers.unshift(observer);
  6393. }
  6394. else {
  6395. this._observers.push(observer);
  6396. }
  6397. if (this._onObserverAdded) {
  6398. this._onObserverAdded(observer);
  6399. }
  6400. return observer;
  6401. };
  6402. /**
  6403. * Remove an Observer from the Observable object
  6404. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6405. */
  6406. Observable.prototype.remove = function (observer) {
  6407. if (!observer) {
  6408. return false;
  6409. }
  6410. var index = this._observers.indexOf(observer);
  6411. if (index !== -1) {
  6412. this._observers.splice(index, 1);
  6413. return true;
  6414. }
  6415. return false;
  6416. };
  6417. /**
  6418. * Remove a callback from the Observable object
  6419. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6420. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6421. */
  6422. Observable.prototype.removeCallback = function (callback, scope) {
  6423. for (var index = 0; index < this._observers.length; index++) {
  6424. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6425. this._observers.splice(index, 1);
  6426. return true;
  6427. }
  6428. }
  6429. return false;
  6430. };
  6431. /**
  6432. * Notify all Observers by calling their respective callback with the given data
  6433. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6434. * @param eventData
  6435. * @param mask
  6436. */
  6437. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6438. if (mask === void 0) { mask = -1; }
  6439. if (!this._observers.length) {
  6440. return true;
  6441. }
  6442. var state = this._eventState;
  6443. state.mask = mask;
  6444. state.target = target;
  6445. state.currentTarget = currentTarget;
  6446. state.skipNextObservers = false;
  6447. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6448. var obs = _a[_i];
  6449. if (obs.mask & mask) {
  6450. if (obs.scope) {
  6451. obs.callback.apply(obs.scope, [eventData, state]);
  6452. }
  6453. else {
  6454. obs.callback(eventData, state);
  6455. }
  6456. }
  6457. if (state.skipNextObservers) {
  6458. return false;
  6459. }
  6460. }
  6461. return true;
  6462. };
  6463. /**
  6464. * Notify a specific observer
  6465. * @param eventData
  6466. * @param mask
  6467. */
  6468. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6469. if (mask === void 0) { mask = -1; }
  6470. var state = this._eventState;
  6471. state.mask = mask;
  6472. state.skipNextObservers = false;
  6473. observer.callback(eventData, state);
  6474. };
  6475. /**
  6476. * return true is the Observable has at least one Observer registered
  6477. */
  6478. Observable.prototype.hasObservers = function () {
  6479. return this._observers.length > 0;
  6480. };
  6481. /**
  6482. * Clear the list of observers
  6483. */
  6484. Observable.prototype.clear = function () {
  6485. this._observers = new Array();
  6486. this._onObserverAdded = null;
  6487. };
  6488. /**
  6489. * Clone the current observable
  6490. */
  6491. Observable.prototype.clone = function () {
  6492. var result = new Observable();
  6493. result._observers = this._observers.slice(0);
  6494. return result;
  6495. };
  6496. /**
  6497. * Does this observable handles observer registered with a given mask
  6498. * @param {number} trigger - the mask to be tested
  6499. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6500. **/
  6501. Observable.prototype.hasSpecificMask = function (mask) {
  6502. if (mask === void 0) { mask = -1; }
  6503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6504. var obs = _a[_i];
  6505. if (obs.mask & mask || obs.mask === mask) {
  6506. return true;
  6507. }
  6508. }
  6509. return false;
  6510. };
  6511. return Observable;
  6512. }());
  6513. BABYLON.Observable = Observable;
  6514. })(BABYLON || (BABYLON = {}));
  6515. //# sourceMappingURL=babylon.observable.js.map
  6516. var BABYLON;
  6517. (function (BABYLON) {
  6518. var SmartArray = /** @class */ (function () {
  6519. function SmartArray(capacity) {
  6520. this.length = 0;
  6521. this.data = new Array(capacity);
  6522. this._id = SmartArray._GlobalId++;
  6523. }
  6524. SmartArray.prototype.push = function (value) {
  6525. this.data[this.length++] = value;
  6526. if (this.length > this.data.length) {
  6527. this.data.length *= 2;
  6528. }
  6529. };
  6530. SmartArray.prototype.forEach = function (func) {
  6531. for (var index = 0; index < this.length; index++) {
  6532. func(this.data[index]);
  6533. }
  6534. };
  6535. SmartArray.prototype.sort = function (compareFn) {
  6536. this.data.sort(compareFn);
  6537. };
  6538. SmartArray.prototype.reset = function () {
  6539. this.length = 0;
  6540. };
  6541. SmartArray.prototype.dispose = function () {
  6542. this.reset();
  6543. if (this.data) {
  6544. this.data.length = 0;
  6545. this.data = [];
  6546. }
  6547. };
  6548. SmartArray.prototype.concat = function (array) {
  6549. if (array.length === 0) {
  6550. return;
  6551. }
  6552. if (this.length + array.length > this.data.length) {
  6553. this.data.length = (this.length + array.length) * 2;
  6554. }
  6555. for (var index = 0; index < array.length; index++) {
  6556. this.data[this.length++] = (array.data || array)[index];
  6557. }
  6558. };
  6559. SmartArray.prototype.indexOf = function (value) {
  6560. var position = this.data.indexOf(value);
  6561. if (position >= this.length) {
  6562. return -1;
  6563. }
  6564. return position;
  6565. };
  6566. SmartArray.prototype.contains = function (value) {
  6567. return this.data.indexOf(value) !== -1;
  6568. };
  6569. // Statics
  6570. SmartArray._GlobalId = 0;
  6571. return SmartArray;
  6572. }());
  6573. BABYLON.SmartArray = SmartArray;
  6574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6575. __extends(SmartArrayNoDuplicate, _super);
  6576. function SmartArrayNoDuplicate() {
  6577. var _this = _super !== null && _super.apply(this, arguments) || this;
  6578. _this._duplicateId = 0;
  6579. return _this;
  6580. }
  6581. SmartArrayNoDuplicate.prototype.push = function (value) {
  6582. _super.prototype.push.call(this, value);
  6583. if (!value.__smartArrayFlags) {
  6584. value.__smartArrayFlags = {};
  6585. }
  6586. value.__smartArrayFlags[this._id] = this._duplicateId;
  6587. };
  6588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6590. return false;
  6591. }
  6592. this.push(value);
  6593. return true;
  6594. };
  6595. SmartArrayNoDuplicate.prototype.reset = function () {
  6596. _super.prototype.reset.call(this);
  6597. this._duplicateId++;
  6598. };
  6599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6600. if (array.length === 0) {
  6601. return;
  6602. }
  6603. if (this.length + array.length > this.data.length) {
  6604. this.data.length = (this.length + array.length) * 2;
  6605. }
  6606. for (var index = 0; index < array.length; index++) {
  6607. var item = (array.data || array)[index];
  6608. this.pushNoDuplicate(item);
  6609. }
  6610. };
  6611. return SmartArrayNoDuplicate;
  6612. }(SmartArray));
  6613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6614. })(BABYLON || (BABYLON = {}));
  6615. //# sourceMappingURL=babylon.smartArray.js.map
  6616. var BABYLON;
  6617. (function (BABYLON) {
  6618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6620. var LoadFileError = /** @class */ (function (_super) {
  6621. __extends(LoadFileError, _super);
  6622. function LoadFileError(message, request) {
  6623. var _this = _super.call(this, message) || this;
  6624. _this.request = request;
  6625. _this.name = "LoadFileError";
  6626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6627. return _this;
  6628. }
  6629. // Polyfill for Object.setPrototypeOf if necessary.
  6630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6631. return LoadFileError;
  6632. }(Error));
  6633. BABYLON.LoadFileError = LoadFileError;
  6634. var RetryStrategy = /** @class */ (function () {
  6635. function RetryStrategy() {
  6636. }
  6637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6638. if (maxRetries === void 0) { maxRetries = 3; }
  6639. if (baseInterval === void 0) { baseInterval = 500; }
  6640. return function (url, request, retryIndex) {
  6641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6642. return -1;
  6643. }
  6644. return Math.pow(2, retryIndex) * baseInterval;
  6645. };
  6646. };
  6647. return RetryStrategy;
  6648. }());
  6649. BABYLON.RetryStrategy = RetryStrategy;
  6650. // Screenshots
  6651. var screenshotCanvas;
  6652. var cloneValue = function (source, destinationObject) {
  6653. if (!source)
  6654. return null;
  6655. if (source instanceof BABYLON.Mesh) {
  6656. return null;
  6657. }
  6658. if (source instanceof BABYLON.SubMesh) {
  6659. return source.clone(destinationObject);
  6660. }
  6661. else if (source.clone) {
  6662. return source.clone();
  6663. }
  6664. return null;
  6665. };
  6666. var Tools = /** @class */ (function () {
  6667. function Tools() {
  6668. }
  6669. /**
  6670. * Interpolates between a and b via alpha
  6671. * @param a The lower value (returned when alpha = 0)
  6672. * @param b The upper value (returned when alpha = 1)
  6673. * @param alpha The interpolation-factor
  6674. * @return The mixed value
  6675. */
  6676. Tools.Mix = function (a, b, alpha) {
  6677. return a * (1 - alpha) + b * alpha;
  6678. };
  6679. Tools.Instantiate = function (className) {
  6680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6681. return Tools.RegisteredExternalClasses[className];
  6682. }
  6683. var arr = className.split(".");
  6684. var fn = (window || this);
  6685. for (var i = 0, len = arr.length; i < len; i++) {
  6686. fn = fn[arr[i]];
  6687. }
  6688. if (typeof fn !== "function") {
  6689. return null;
  6690. }
  6691. return fn;
  6692. };
  6693. Tools.SetImmediate = function (action) {
  6694. if (window.setImmediate) {
  6695. window.setImmediate(action);
  6696. }
  6697. else {
  6698. setTimeout(action, 1);
  6699. }
  6700. };
  6701. Tools.IsExponentOfTwo = function (value) {
  6702. var count = 1;
  6703. do {
  6704. count *= 2;
  6705. } while (count < value);
  6706. return count === value;
  6707. };
  6708. /**
  6709. * Find the next highest power of two.
  6710. * @param x Number to start search from.
  6711. * @return Next highest power of two.
  6712. */
  6713. Tools.CeilingPOT = function (x) {
  6714. x--;
  6715. x |= x >> 1;
  6716. x |= x >> 2;
  6717. x |= x >> 4;
  6718. x |= x >> 8;
  6719. x |= x >> 16;
  6720. x++;
  6721. return x;
  6722. };
  6723. /**
  6724. * Find the next lowest power of two.
  6725. * @param x Number to start search from.
  6726. * @return Next lowest power of two.
  6727. */
  6728. Tools.FloorPOT = function (x) {
  6729. x = x | (x >> 1);
  6730. x = x | (x >> 2);
  6731. x = x | (x >> 4);
  6732. x = x | (x >> 8);
  6733. x = x | (x >> 16);
  6734. return x - (x >> 1);
  6735. };
  6736. /**
  6737. * Find the nearest power of two.
  6738. * @param x Number to start search from.
  6739. * @return Next nearest power of two.
  6740. */
  6741. Tools.NearestPOT = function (x) {
  6742. var c = Tools.CeilingPOT(x);
  6743. var f = Tools.FloorPOT(x);
  6744. return (c - x) > (x - f) ? f : c;
  6745. };
  6746. Tools.GetExponentOfTwo = function (value, max, mode) {
  6747. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6748. var pot;
  6749. switch (mode) {
  6750. case BABYLON.Engine.SCALEMODE_FLOOR:
  6751. pot = Tools.FloorPOT(value);
  6752. break;
  6753. case BABYLON.Engine.SCALEMODE_NEAREST:
  6754. pot = Tools.NearestPOT(value);
  6755. break;
  6756. case BABYLON.Engine.SCALEMODE_CEILING:
  6757. default:
  6758. pot = Tools.CeilingPOT(value);
  6759. break;
  6760. }
  6761. return Math.min(pot, max);
  6762. };
  6763. Tools.GetFilename = function (path) {
  6764. var index = path.lastIndexOf("/");
  6765. if (index < 0)
  6766. return path;
  6767. return path.substring(index + 1);
  6768. };
  6769. Tools.GetFolderPath = function (uri) {
  6770. var index = uri.lastIndexOf("/");
  6771. if (index < 0)
  6772. return "";
  6773. return uri.substring(0, index + 1);
  6774. };
  6775. Tools.GetDOMTextContent = function (element) {
  6776. var result = "";
  6777. var child = element.firstChild;
  6778. while (child) {
  6779. if (child.nodeType === 3) {
  6780. result += child.textContent;
  6781. }
  6782. child = child.nextSibling;
  6783. }
  6784. return result;
  6785. };
  6786. Tools.ToDegrees = function (angle) {
  6787. return angle * 180 / Math.PI;
  6788. };
  6789. Tools.ToRadians = function (angle) {
  6790. return angle * Math.PI / 180;
  6791. };
  6792. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6793. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6794. var output = "";
  6795. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6796. var i = 0;
  6797. var bytes = new Uint8Array(buffer);
  6798. while (i < bytes.length) {
  6799. chr1 = bytes[i++];
  6800. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6801. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6802. enc1 = chr1 >> 2;
  6803. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6804. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6805. enc4 = chr3 & 63;
  6806. if (isNaN(chr2)) {
  6807. enc3 = enc4 = 64;
  6808. }
  6809. else if (isNaN(chr3)) {
  6810. enc4 = 64;
  6811. }
  6812. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6813. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6814. }
  6815. return "data:image/png;base64," + output;
  6816. };
  6817. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6818. if (bias === void 0) { bias = null; }
  6819. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6820. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6821. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6822. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6823. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6824. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6825. }
  6826. if (bias) {
  6827. minimum.x -= minimum.x * bias.x + bias.y;
  6828. minimum.y -= minimum.y * bias.x + bias.y;
  6829. minimum.z -= minimum.z * bias.x + bias.y;
  6830. maximum.x += maximum.x * bias.x + bias.y;
  6831. maximum.y += maximum.y * bias.x + bias.y;
  6832. maximum.z += maximum.z * bias.x + bias.y;
  6833. }
  6834. return {
  6835. minimum: minimum,
  6836. maximum: maximum
  6837. };
  6838. };
  6839. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6840. if (bias === void 0) { bias = null; }
  6841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6843. if (!stride) {
  6844. stride = 3;
  6845. }
  6846. for (var index = start; index < start + count; index++) {
  6847. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6848. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6849. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6850. }
  6851. if (bias) {
  6852. minimum.x -= minimum.x * bias.x + bias.y;
  6853. minimum.y -= minimum.y * bias.x + bias.y;
  6854. minimum.z -= minimum.z * bias.x + bias.y;
  6855. maximum.x += maximum.x * bias.x + bias.y;
  6856. maximum.y += maximum.y * bias.x + bias.y;
  6857. maximum.z += maximum.z * bias.x + bias.y;
  6858. }
  6859. return {
  6860. minimum: minimum,
  6861. maximum: maximum
  6862. };
  6863. };
  6864. Tools.Vector2ArrayFeeder = function (array) {
  6865. return function (index) {
  6866. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6867. var length = isFloatArray ? array.length / 2 : array.length;
  6868. if (index >= length) {
  6869. return null;
  6870. }
  6871. if (isFloatArray) {
  6872. var fa = array;
  6873. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6874. }
  6875. var a = array;
  6876. return a[index];
  6877. };
  6878. };
  6879. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6880. if (bias === void 0) { bias = null; }
  6881. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6882. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6883. var i = 0;
  6884. var cur = feeder(i++);
  6885. while (cur) {
  6886. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6887. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6888. cur = feeder(i++);
  6889. }
  6890. if (bias) {
  6891. minimum.x -= minimum.x * bias.x + bias.y;
  6892. minimum.y -= minimum.y * bias.x + bias.y;
  6893. maximum.x += maximum.x * bias.x + bias.y;
  6894. maximum.y += maximum.y * bias.x + bias.y;
  6895. }
  6896. return {
  6897. minimum: minimum,
  6898. maximum: maximum
  6899. };
  6900. };
  6901. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6902. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6903. return null;
  6904. return Array.isArray(obj) ? obj : [obj];
  6905. };
  6906. // Misc.
  6907. Tools.GetPointerPrefix = function () {
  6908. var eventPrefix = "pointer";
  6909. // Check if pointer events are supported
  6910. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6911. eventPrefix = "mouse";
  6912. }
  6913. return eventPrefix;
  6914. };
  6915. /**
  6916. * @param func - the function to be called
  6917. * @param requester - the object that will request the next frame. Falls back to window.
  6918. */
  6919. Tools.QueueNewFrame = function (func, requester) {
  6920. if (!Tools.IsWindowObjectExist()) {
  6921. return setTimeout(func, 16);
  6922. }
  6923. if (!requester) {
  6924. requester = window;
  6925. }
  6926. if (requester.requestAnimationFrame) {
  6927. return requester.requestAnimationFrame(func);
  6928. }
  6929. else if (requester.msRequestAnimationFrame) {
  6930. return requester.msRequestAnimationFrame(func);
  6931. }
  6932. else if (requester.webkitRequestAnimationFrame) {
  6933. return requester.webkitRequestAnimationFrame(func);
  6934. }
  6935. else if (requester.mozRequestAnimationFrame) {
  6936. return requester.mozRequestAnimationFrame(func);
  6937. }
  6938. else if (requester.oRequestAnimationFrame) {
  6939. return requester.oRequestAnimationFrame(func);
  6940. }
  6941. else {
  6942. return window.setTimeout(func, 16);
  6943. }
  6944. };
  6945. Tools.RequestFullscreen = function (element) {
  6946. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6947. if (!requestFunction)
  6948. return;
  6949. requestFunction.call(element);
  6950. };
  6951. Tools.ExitFullscreen = function () {
  6952. if (document.exitFullscreen) {
  6953. document.exitFullscreen();
  6954. }
  6955. else if (document.mozCancelFullScreen) {
  6956. document.mozCancelFullScreen();
  6957. }
  6958. else if (document.webkitCancelFullScreen) {
  6959. document.webkitCancelFullScreen();
  6960. }
  6961. else if (document.msCancelFullScreen) {
  6962. document.msCancelFullScreen();
  6963. }
  6964. };
  6965. Tools.SetCorsBehavior = function (url, element) {
  6966. if (url && url.indexOf("data:") === 0) {
  6967. return;
  6968. }
  6969. if (Tools.CorsBehavior) {
  6970. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6971. element.crossOrigin = Tools.CorsBehavior;
  6972. }
  6973. else {
  6974. var result = Tools.CorsBehavior(url);
  6975. if (result) {
  6976. element.crossOrigin = result;
  6977. }
  6978. }
  6979. }
  6980. };
  6981. // External files
  6982. Tools.CleanUrl = function (url) {
  6983. url = url.replace(/#/mg, "%23");
  6984. return url;
  6985. };
  6986. Tools.LoadImage = function (url, onLoad, onError, database) {
  6987. if (url instanceof ArrayBuffer) {
  6988. url = Tools.EncodeArrayBufferTobase64(url);
  6989. }
  6990. url = Tools.CleanUrl(url);
  6991. url = Tools.PreprocessUrl(url);
  6992. var img = new Image();
  6993. Tools.SetCorsBehavior(url, img);
  6994. img.onload = function () {
  6995. onLoad(img);
  6996. };
  6997. img.onerror = function (err) {
  6998. Tools.Error("Error while trying to load image: " + url);
  6999. if (onError) {
  7000. onError("Error while trying to load image: " + url, err);
  7001. }
  7002. };
  7003. var noIndexedDB = function () {
  7004. img.src = url;
  7005. };
  7006. var loadFromIndexedDB = function () {
  7007. if (database) {
  7008. database.loadImageFromDB(url, img);
  7009. }
  7010. };
  7011. //ANY database to do!
  7012. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7013. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7014. }
  7015. else {
  7016. if (url.indexOf("file:") !== -1) {
  7017. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7018. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7019. try {
  7020. var blobURL;
  7021. try {
  7022. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7023. }
  7024. catch (ex) {
  7025. // Chrome doesn't support oneTimeOnly parameter
  7026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7027. }
  7028. img.src = blobURL;
  7029. }
  7030. catch (e) {
  7031. img.src = "";
  7032. }
  7033. return img;
  7034. }
  7035. }
  7036. noIndexedDB();
  7037. }
  7038. return img;
  7039. };
  7040. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7041. url = Tools.CleanUrl(url);
  7042. url = Tools.PreprocessUrl(url);
  7043. // If file and file input are set
  7044. if (url.indexOf("file:") !== -1) {
  7045. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7046. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7047. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7048. }
  7049. }
  7050. var loadUrl = Tools.BaseUrl + url;
  7051. var aborted = false;
  7052. var fileRequest = {
  7053. onCompleteObservable: new BABYLON.Observable(),
  7054. abort: function () { return aborted = true; },
  7055. };
  7056. var requestFile = function () {
  7057. var request = new XMLHttpRequest();
  7058. var retryHandle = null;
  7059. fileRequest.abort = function () {
  7060. aborted = true;
  7061. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7062. request.abort();
  7063. }
  7064. if (retryHandle !== null) {
  7065. clearTimeout(retryHandle);
  7066. retryHandle = null;
  7067. }
  7068. };
  7069. var retryLoop = function (retryIndex) {
  7070. request.open('GET', loadUrl, true);
  7071. if (useArrayBuffer) {
  7072. request.responseType = "arraybuffer";
  7073. }
  7074. if (onProgress) {
  7075. request.addEventListener("progress", onProgress);
  7076. }
  7077. var onLoadEnd = function () {
  7078. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7079. };
  7080. request.addEventListener("loadend", onLoadEnd);
  7081. var onReadyStateChange = function () {
  7082. if (aborted) {
  7083. return;
  7084. }
  7085. // In case of undefined state in some browsers.
  7086. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7087. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7088. request.removeEventListener("readystatechange", onReadyStateChange);
  7089. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7090. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7091. return;
  7092. }
  7093. var retryStrategy = Tools.DefaultRetryStrategy;
  7094. if (retryStrategy) {
  7095. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7096. if (waitTime !== -1) {
  7097. // Prevent the request from completing for retry.
  7098. request.removeEventListener("loadend", onLoadEnd);
  7099. request = new XMLHttpRequest();
  7100. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7101. return;
  7102. }
  7103. }
  7104. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7105. if (onError) {
  7106. onError(request, e);
  7107. }
  7108. else {
  7109. throw e;
  7110. }
  7111. }
  7112. };
  7113. request.addEventListener("readystatechange", onReadyStateChange);
  7114. request.send();
  7115. };
  7116. retryLoop(0);
  7117. };
  7118. // Caching all files
  7119. if (database && database.enableSceneOffline) {
  7120. var noIndexedDB_1 = function () {
  7121. if (!aborted) {
  7122. requestFile();
  7123. }
  7124. };
  7125. var loadFromIndexedDB = function () {
  7126. // TODO: database needs to support aborting and should return a IFileRequest
  7127. if (aborted) {
  7128. return;
  7129. }
  7130. if (database) {
  7131. database.loadFileFromDB(url, function (data) {
  7132. if (!aborted) {
  7133. onSuccess(data);
  7134. }
  7135. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7136. }, onProgress ? function (event) {
  7137. if (!aborted) {
  7138. onProgress(event);
  7139. }
  7140. } : undefined, noIndexedDB_1, useArrayBuffer);
  7141. }
  7142. };
  7143. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7144. }
  7145. else {
  7146. requestFile();
  7147. }
  7148. return fileRequest;
  7149. };
  7150. /**
  7151. * Load a script (identified by an url). When the url returns, the
  7152. * content of this file is added into a new script element, attached to the DOM (body element)
  7153. */
  7154. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7155. var head = document.getElementsByTagName('head')[0];
  7156. var script = document.createElement('script');
  7157. script.type = 'text/javascript';
  7158. script.src = scriptUrl;
  7159. script.onload = function () {
  7160. if (onSuccess) {
  7161. onSuccess();
  7162. }
  7163. };
  7164. script.onerror = function (e) {
  7165. if (onError) {
  7166. onError("Unable to load script", e);
  7167. }
  7168. };
  7169. head.appendChild(script);
  7170. };
  7171. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7172. var reader = new FileReader();
  7173. var request = {
  7174. onCompleteObservable: new BABYLON.Observable(),
  7175. abort: function () { return reader.abort(); },
  7176. };
  7177. reader.onloadend = function (e) {
  7178. request.onCompleteObservable.notifyObservers(request);
  7179. };
  7180. reader.onload = function (e) {
  7181. //target doesn't have result from ts 1.3
  7182. callback(e.target['result']);
  7183. };
  7184. reader.onprogress = progressCallback;
  7185. reader.readAsDataURL(fileToLoad);
  7186. return request;
  7187. };
  7188. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7189. var reader = new FileReader();
  7190. var request = {
  7191. onCompleteObservable: new BABYLON.Observable(),
  7192. abort: function () { return reader.abort(); },
  7193. };
  7194. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7195. reader.onerror = function (e) {
  7196. Tools.Log("Error while reading file: " + fileToLoad.name);
  7197. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7198. };
  7199. reader.onload = function (e) {
  7200. //target doesn't have result from ts 1.3
  7201. callback(e.target['result']);
  7202. };
  7203. if (progressCallBack) {
  7204. reader.onprogress = progressCallBack;
  7205. }
  7206. if (!useArrayBuffer) {
  7207. // Asynchronous read
  7208. reader.readAsText(fileToLoad);
  7209. }
  7210. else {
  7211. reader.readAsArrayBuffer(fileToLoad);
  7212. }
  7213. return request;
  7214. };
  7215. //returns a downloadable url to a file content.
  7216. Tools.FileAsURL = function (content) {
  7217. var fileBlob = new Blob([content]);
  7218. var url = window.URL || window.webkitURL;
  7219. var link = url.createObjectURL(fileBlob);
  7220. return link;
  7221. };
  7222. // Misc.
  7223. Tools.Format = function (value, decimals) {
  7224. if (decimals === void 0) { decimals = 2; }
  7225. return value.toFixed(decimals);
  7226. };
  7227. Tools.CheckExtends = function (v, min, max) {
  7228. if (v.x < min.x)
  7229. min.x = v.x;
  7230. if (v.y < min.y)
  7231. min.y = v.y;
  7232. if (v.z < min.z)
  7233. min.z = v.z;
  7234. if (v.x > max.x)
  7235. max.x = v.x;
  7236. if (v.y > max.y)
  7237. max.y = v.y;
  7238. if (v.z > max.z)
  7239. max.z = v.z;
  7240. };
  7241. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7242. for (var prop in source) {
  7243. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7244. continue;
  7245. }
  7246. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7247. continue;
  7248. }
  7249. var sourceValue = source[prop];
  7250. var typeOfSourceValue = typeof sourceValue;
  7251. if (typeOfSourceValue === "function") {
  7252. continue;
  7253. }
  7254. if (typeOfSourceValue === "object") {
  7255. if (sourceValue instanceof Array) {
  7256. destination[prop] = [];
  7257. if (sourceValue.length > 0) {
  7258. if (typeof sourceValue[0] == "object") {
  7259. for (var index = 0; index < sourceValue.length; index++) {
  7260. var clonedValue = cloneValue(sourceValue[index], destination);
  7261. if (destination[prop].indexOf(clonedValue) === -1) {
  7262. destination[prop].push(clonedValue);
  7263. }
  7264. }
  7265. }
  7266. else {
  7267. destination[prop] = sourceValue.slice(0);
  7268. }
  7269. }
  7270. }
  7271. else {
  7272. destination[prop] = cloneValue(sourceValue, destination);
  7273. }
  7274. }
  7275. else {
  7276. destination[prop] = sourceValue;
  7277. }
  7278. }
  7279. };
  7280. Tools.IsEmpty = function (obj) {
  7281. for (var i in obj) {
  7282. if (obj.hasOwnProperty(i)) {
  7283. return false;
  7284. }
  7285. }
  7286. return true;
  7287. };
  7288. Tools.RegisterTopRootEvents = function (events) {
  7289. for (var index = 0; index < events.length; index++) {
  7290. var event = events[index];
  7291. window.addEventListener(event.name, event.handler, false);
  7292. try {
  7293. if (window.parent) {
  7294. window.parent.addEventListener(event.name, event.handler, false);
  7295. }
  7296. }
  7297. catch (e) {
  7298. // Silently fails...
  7299. }
  7300. }
  7301. };
  7302. Tools.UnregisterTopRootEvents = function (events) {
  7303. for (var index = 0; index < events.length; index++) {
  7304. var event = events[index];
  7305. window.removeEventListener(event.name, event.handler);
  7306. try {
  7307. if (window.parent) {
  7308. window.parent.removeEventListener(event.name, event.handler);
  7309. }
  7310. }
  7311. catch (e) {
  7312. // Silently fails...
  7313. }
  7314. }
  7315. };
  7316. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7317. if (mimeType === void 0) { mimeType = "image/png"; }
  7318. // Read the contents of the framebuffer
  7319. var numberOfChannelsByLine = width * 4;
  7320. var halfHeight = height / 2;
  7321. //Reading datas from WebGL
  7322. var data = engine.readPixels(0, 0, width, height);
  7323. //To flip image on Y axis.
  7324. for (var i = 0; i < halfHeight; i++) {
  7325. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7326. var currentCell = j + i * numberOfChannelsByLine;
  7327. var targetLine = height - i - 1;
  7328. var targetCell = j + targetLine * numberOfChannelsByLine;
  7329. var temp = data[currentCell];
  7330. data[currentCell] = data[targetCell];
  7331. data[targetCell] = temp;
  7332. }
  7333. }
  7334. // Create a 2D canvas to store the result
  7335. if (!screenshotCanvas) {
  7336. screenshotCanvas = document.createElement('canvas');
  7337. }
  7338. screenshotCanvas.width = width;
  7339. screenshotCanvas.height = height;
  7340. var context = screenshotCanvas.getContext('2d');
  7341. if (context) {
  7342. // Copy the pixels to a 2D canvas
  7343. var imageData = context.createImageData(width, height);
  7344. var castData = (imageData.data);
  7345. castData.set(data);
  7346. context.putImageData(imageData, 0, 0);
  7347. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7348. }
  7349. };
  7350. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7351. if (mimeType === void 0) { mimeType = "image/png"; }
  7352. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7353. if (successCallback) {
  7354. successCallback(base64Image);
  7355. }
  7356. else {
  7357. // We need HTMLCanvasElement.toBlob for HD screenshots
  7358. if (!screenshotCanvas.toBlob) {
  7359. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7360. screenshotCanvas.toBlob = function (callback, type, quality) {
  7361. var _this = this;
  7362. setTimeout(function () {
  7363. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7364. for (var i = 0; i < len; i++) {
  7365. arr[i] = binStr.charCodeAt(i);
  7366. }
  7367. callback(new Blob([arr], { type: type || 'image/png' }));
  7368. });
  7369. };
  7370. }
  7371. screenshotCanvas.toBlob(function (blob) {
  7372. var url = URL.createObjectURL(blob);
  7373. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7374. if (("download" in document.createElement("a"))) {
  7375. var a = window.document.createElement("a");
  7376. a.href = url;
  7377. if (fileName) {
  7378. a.setAttribute("download", fileName);
  7379. }
  7380. else {
  7381. var date = new Date();
  7382. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7383. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7384. }
  7385. window.document.body.appendChild(a);
  7386. a.addEventListener("click", function () {
  7387. if (a.parentElement) {
  7388. a.parentElement.removeChild(a);
  7389. }
  7390. });
  7391. a.click();
  7392. }
  7393. else {
  7394. var newWindow = window.open("");
  7395. if (!newWindow)
  7396. return;
  7397. var img = newWindow.document.createElement("img");
  7398. img.onload = function () {
  7399. // no longer need to read the blob so it's revoked
  7400. URL.revokeObjectURL(url);
  7401. };
  7402. img.src = url;
  7403. newWindow.document.body.appendChild(img);
  7404. }
  7405. });
  7406. }
  7407. };
  7408. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7409. if (mimeType === void 0) { mimeType = "image/png"; }
  7410. var width;
  7411. var height;
  7412. // If a precision value is specified
  7413. if (size.precision) {
  7414. width = Math.round(engine.getRenderWidth() * size.precision);
  7415. height = Math.round(width / engine.getAspectRatio(camera));
  7416. }
  7417. else if (size.width && size.height) {
  7418. width = size.width;
  7419. height = size.height;
  7420. }
  7421. else if (size.width && !size.height) {
  7422. width = size.width;
  7423. height = Math.round(width / engine.getAspectRatio(camera));
  7424. }
  7425. else if (size.height && !size.width) {
  7426. height = size.height;
  7427. width = Math.round(height * engine.getAspectRatio(camera));
  7428. }
  7429. else if (!isNaN(size)) {
  7430. height = size;
  7431. width = size;
  7432. }
  7433. else {
  7434. Tools.Error("Invalid 'size' parameter !");
  7435. return;
  7436. }
  7437. if (!screenshotCanvas) {
  7438. screenshotCanvas = document.createElement('canvas');
  7439. }
  7440. screenshotCanvas.width = width;
  7441. screenshotCanvas.height = height;
  7442. var renderContext = screenshotCanvas.getContext("2d");
  7443. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7444. var newWidth = width;
  7445. var newHeight = newWidth / ratio;
  7446. if (newHeight > height) {
  7447. newHeight = height;
  7448. newWidth = newHeight * ratio;
  7449. }
  7450. var offsetX = Math.max(0, width - newWidth) / 2;
  7451. var offsetY = Math.max(0, height - newHeight) / 2;
  7452. var renderingCanvas = engine.getRenderingCanvas();
  7453. if (renderContext && renderingCanvas) {
  7454. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7455. }
  7456. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7457. };
  7458. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7459. if (mimeType === void 0) { mimeType = "image/png"; }
  7460. if (samples === void 0) { samples = 1; }
  7461. if (antialiasing === void 0) { antialiasing = false; }
  7462. var width;
  7463. var height;
  7464. //If a precision value is specified
  7465. if (size.precision) {
  7466. width = Math.round(engine.getRenderWidth() * size.precision);
  7467. height = Math.round(width / engine.getAspectRatio(camera));
  7468. size = { width: width, height: height };
  7469. }
  7470. else if (size.width && size.height) {
  7471. width = size.width;
  7472. height = size.height;
  7473. }
  7474. else if (size.width && !size.height) {
  7475. width = size.width;
  7476. height = Math.round(width / engine.getAspectRatio(camera));
  7477. size = { width: width, height: height };
  7478. }
  7479. else if (size.height && !size.width) {
  7480. height = size.height;
  7481. width = Math.round(height * engine.getAspectRatio(camera));
  7482. size = { width: width, height: height };
  7483. }
  7484. else if (!isNaN(size)) {
  7485. height = size;
  7486. width = size;
  7487. }
  7488. else {
  7489. Tools.Error("Invalid 'size' parameter !");
  7490. return;
  7491. }
  7492. var scene = camera.getScene();
  7493. var previousCamera = null;
  7494. if (scene.activeCamera !== camera) {
  7495. previousCamera = scene.activeCamera;
  7496. scene.activeCamera = camera;
  7497. }
  7498. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7499. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7500. texture.renderList = null;
  7501. texture.samples = samples;
  7502. if (antialiasing) {
  7503. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7504. }
  7505. texture.onAfterRenderObservable.add(function () {
  7506. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7507. });
  7508. scene.incrementRenderId();
  7509. scene.resetCachedMaterial();
  7510. texture.render(true);
  7511. texture.dispose();
  7512. if (previousCamera) {
  7513. scene.activeCamera = previousCamera;
  7514. }
  7515. camera.getProjectionMatrix(true); // Force cache refresh;
  7516. };
  7517. // XHR response validator for local file scenario
  7518. Tools.ValidateXHRData = function (xhr, dataType) {
  7519. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7520. if (dataType === void 0) { dataType = 7; }
  7521. try {
  7522. if (dataType & 1) {
  7523. if (xhr.responseText && xhr.responseText.length > 0) {
  7524. return true;
  7525. }
  7526. else if (dataType === 1) {
  7527. return false;
  7528. }
  7529. }
  7530. if (dataType & 2) {
  7531. // Check header width and height since there is no "TGA" magic number
  7532. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7533. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7534. return true;
  7535. }
  7536. else if (dataType === 2) {
  7537. return false;
  7538. }
  7539. }
  7540. if (dataType & 4) {
  7541. // Check for the "DDS" magic number
  7542. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7543. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7544. return true;
  7545. }
  7546. else {
  7547. return false;
  7548. }
  7549. }
  7550. }
  7551. catch (e) {
  7552. // Global protection
  7553. }
  7554. return false;
  7555. };
  7556. /**
  7557. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7558. * Be aware Math.random() could cause collisions, but:
  7559. * "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"
  7560. */
  7561. Tools.RandomId = function () {
  7562. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7563. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7564. return v.toString(16);
  7565. });
  7566. };
  7567. Object.defineProperty(Tools, "NoneLogLevel", {
  7568. get: function () {
  7569. return Tools._NoneLogLevel;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Tools, "MessageLogLevel", {
  7575. get: function () {
  7576. return Tools._MessageLogLevel;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Tools, "WarningLogLevel", {
  7582. get: function () {
  7583. return Tools._WarningLogLevel;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Tools, "ErrorLogLevel", {
  7589. get: function () {
  7590. return Tools._ErrorLogLevel;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Tools, "AllLogLevel", {
  7596. get: function () {
  7597. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Tools._AddLogEntry = function (entry) {
  7603. Tools._LogCache = entry + Tools._LogCache;
  7604. if (Tools.OnNewCacheEntry) {
  7605. Tools.OnNewCacheEntry(entry);
  7606. }
  7607. };
  7608. Tools._FormatMessage = function (message) {
  7609. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7610. var date = new Date();
  7611. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7612. };
  7613. Tools._LogDisabled = function (message) {
  7614. // nothing to do
  7615. };
  7616. Tools._LogEnabled = function (message) {
  7617. var formattedMessage = Tools._FormatMessage(message);
  7618. console.log("BJS - " + formattedMessage);
  7619. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7620. Tools._AddLogEntry(entry);
  7621. };
  7622. Tools._WarnDisabled = function (message) {
  7623. // nothing to do
  7624. };
  7625. Tools._WarnEnabled = function (message) {
  7626. var formattedMessage = Tools._FormatMessage(message);
  7627. console.warn("BJS - " + formattedMessage);
  7628. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7629. Tools._AddLogEntry(entry);
  7630. };
  7631. Tools._ErrorDisabled = function (message) {
  7632. // nothing to do
  7633. };
  7634. Tools._ErrorEnabled = function (message) {
  7635. Tools.errorsCount++;
  7636. var formattedMessage = Tools._FormatMessage(message);
  7637. console.error("BJS - " + formattedMessage);
  7638. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7639. Tools._AddLogEntry(entry);
  7640. };
  7641. Object.defineProperty(Tools, "LogCache", {
  7642. get: function () {
  7643. return Tools._LogCache;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. Tools.ClearLogCache = function () {
  7649. Tools._LogCache = "";
  7650. Tools.errorsCount = 0;
  7651. };
  7652. Object.defineProperty(Tools, "LogLevels", {
  7653. set: function (level) {
  7654. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7655. Tools.Log = Tools._LogEnabled;
  7656. }
  7657. else {
  7658. Tools.Log = Tools._LogDisabled;
  7659. }
  7660. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7661. Tools.Warn = Tools._WarnEnabled;
  7662. }
  7663. else {
  7664. Tools.Warn = Tools._WarnDisabled;
  7665. }
  7666. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7667. Tools.Error = Tools._ErrorEnabled;
  7668. }
  7669. else {
  7670. Tools.Error = Tools._ErrorDisabled;
  7671. }
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Tools.IsWindowObjectExist = function () {
  7677. return (typeof window) !== "undefined";
  7678. };
  7679. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7680. get: function () {
  7681. return Tools._PerformanceNoneLogLevel;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7687. get: function () {
  7688. return Tools._PerformanceUserMarkLogLevel;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7694. get: function () {
  7695. return Tools._PerformanceConsoleLogLevel;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7701. set: function (level) {
  7702. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7703. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7704. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7705. return;
  7706. }
  7707. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7708. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7709. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7710. return;
  7711. }
  7712. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7713. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7719. };
  7720. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7721. };
  7722. Tools._StartUserMark = function (counterName, condition) {
  7723. if (condition === void 0) { condition = true; }
  7724. if (!Tools._performance) {
  7725. if (!Tools.IsWindowObjectExist()) {
  7726. return;
  7727. }
  7728. Tools._performance = window.performance;
  7729. }
  7730. if (!condition || !Tools._performance.mark) {
  7731. return;
  7732. }
  7733. Tools._performance.mark(counterName + "-Begin");
  7734. };
  7735. Tools._EndUserMark = function (counterName, condition) {
  7736. if (condition === void 0) { condition = true; }
  7737. if (!condition || !Tools._performance.mark) {
  7738. return;
  7739. }
  7740. Tools._performance.mark(counterName + "-End");
  7741. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7742. };
  7743. Tools._StartPerformanceConsole = function (counterName, condition) {
  7744. if (condition === void 0) { condition = true; }
  7745. if (!condition) {
  7746. return;
  7747. }
  7748. Tools._StartUserMark(counterName, condition);
  7749. if (console.time) {
  7750. console.time(counterName);
  7751. }
  7752. };
  7753. Tools._EndPerformanceConsole = function (counterName, condition) {
  7754. if (condition === void 0) { condition = true; }
  7755. if (!condition) {
  7756. return;
  7757. }
  7758. Tools._EndUserMark(counterName, condition);
  7759. if (console.time) {
  7760. console.timeEnd(counterName);
  7761. }
  7762. };
  7763. Object.defineProperty(Tools, "Now", {
  7764. get: function () {
  7765. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7766. return window.performance.now();
  7767. }
  7768. return new Date().getTime();
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. /**
  7774. * This method will return the name of the class used to create the instance of the given object.
  7775. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7776. * @param object the object to get the class name from
  7777. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7778. */
  7779. Tools.GetClassName = function (object, isType) {
  7780. if (isType === void 0) { isType = false; }
  7781. var name = null;
  7782. if (!isType && object.getClassName) {
  7783. name = object.getClassName();
  7784. }
  7785. else {
  7786. if (object instanceof Object) {
  7787. var classObj = isType ? object : Object.getPrototypeOf(object);
  7788. name = classObj.constructor["__bjsclassName__"];
  7789. }
  7790. if (!name) {
  7791. name = typeof object;
  7792. }
  7793. }
  7794. return name;
  7795. };
  7796. Tools.First = function (array, predicate) {
  7797. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7798. var el = array_1[_i];
  7799. if (predicate(el)) {
  7800. return el;
  7801. }
  7802. }
  7803. return null;
  7804. };
  7805. /**
  7806. * This method will return the name of the full name of the class, including its owning module (if any).
  7807. * 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).
  7808. * @param object the object to get the class name from
  7809. * @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.
  7810. */
  7811. Tools.getFullClassName = function (object, isType) {
  7812. if (isType === void 0) { isType = false; }
  7813. var className = null;
  7814. var moduleName = null;
  7815. if (!isType && object.getClassName) {
  7816. className = object.getClassName();
  7817. }
  7818. else {
  7819. if (object instanceof Object) {
  7820. var classObj = isType ? object : Object.getPrototypeOf(object);
  7821. className = classObj.constructor["__bjsclassName__"];
  7822. moduleName = classObj.constructor["__bjsmoduleName__"];
  7823. }
  7824. if (!className) {
  7825. className = typeof object;
  7826. }
  7827. }
  7828. if (!className) {
  7829. return null;
  7830. }
  7831. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7832. };
  7833. /**
  7834. * 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.
  7835. * @param array
  7836. */
  7837. Tools.arrayOrStringFeeder = function (array) {
  7838. return function (index) {
  7839. if (index >= array.length) {
  7840. return null;
  7841. }
  7842. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7843. if (val && val.getHashCode) {
  7844. val = val.getHashCode();
  7845. }
  7846. if (typeof val === "string") {
  7847. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7848. }
  7849. return val;
  7850. };
  7851. };
  7852. /**
  7853. * Compute the hashCode of a stream of number
  7854. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7855. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7856. * @return the hash code computed
  7857. */
  7858. Tools.hashCodeFromStream = function (feeder) {
  7859. // Based from here: http://stackoverflow.com/a/7616484/802124
  7860. var hash = 0;
  7861. var index = 0;
  7862. var chr = feeder(index++);
  7863. while (chr != null) {
  7864. hash = ((hash << 5) - hash) + chr;
  7865. hash |= 0; // Convert to 32bit integer
  7866. chr = feeder(index++);
  7867. }
  7868. return hash;
  7869. };
  7870. Tools.BaseUrl = "";
  7871. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7872. /**
  7873. * Default behaviour for cors in the application.
  7874. * It can be a string if the expected behavior is identical in the entire app.
  7875. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7876. */
  7877. Tools.CorsBehavior = "anonymous";
  7878. Tools.UseFallbackTexture = true;
  7879. /**
  7880. * Use this object to register external classes like custom textures or material
  7881. * to allow the laoders to instantiate them
  7882. */
  7883. Tools.RegisteredExternalClasses = {};
  7884. // Used in case of a texture loading problem
  7885. 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";
  7886. Tools.PreprocessUrl = function (url) {
  7887. return url;
  7888. };
  7889. // Logs
  7890. Tools._NoneLogLevel = 0;
  7891. Tools._MessageLogLevel = 1;
  7892. Tools._WarningLogLevel = 2;
  7893. Tools._ErrorLogLevel = 4;
  7894. Tools._LogCache = "";
  7895. Tools.errorsCount = 0;
  7896. Tools.Log = Tools._LogEnabled;
  7897. Tools.Warn = Tools._WarnEnabled;
  7898. Tools.Error = Tools._ErrorEnabled;
  7899. // Performances
  7900. Tools._PerformanceNoneLogLevel = 0;
  7901. Tools._PerformanceUserMarkLogLevel = 1;
  7902. Tools._PerformanceConsoleLogLevel = 2;
  7903. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7904. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7905. return Tools;
  7906. }());
  7907. BABYLON.Tools = Tools;
  7908. /**
  7909. * This class is used to track a performance counter which is number based.
  7910. * The user has access to many properties which give statistics of different nature
  7911. *
  7912. * The implementer can track two kinds of Performance Counter: time and count
  7913. * 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.
  7914. * 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.
  7915. */
  7916. var PerfCounter = /** @class */ (function () {
  7917. function PerfCounter() {
  7918. this._startMonitoringTime = 0;
  7919. this._min = 0;
  7920. this._max = 0;
  7921. this._average = 0;
  7922. this._lastSecAverage = 0;
  7923. this._current = 0;
  7924. this._totalValueCount = 0;
  7925. this._totalAccumulated = 0;
  7926. this._lastSecAccumulated = 0;
  7927. this._lastSecTime = 0;
  7928. this._lastSecValueCount = 0;
  7929. }
  7930. Object.defineProperty(PerfCounter.prototype, "min", {
  7931. /**
  7932. * Returns the smallest value ever
  7933. */
  7934. get: function () {
  7935. return this._min;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(PerfCounter.prototype, "max", {
  7941. /**
  7942. * Returns the biggest value ever
  7943. */
  7944. get: function () {
  7945. return this._max;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(PerfCounter.prototype, "average", {
  7951. /**
  7952. * Returns the average value since the performance counter is running
  7953. */
  7954. get: function () {
  7955. return this._average;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7961. /**
  7962. * Returns the average value of the last second the counter was monitored
  7963. */
  7964. get: function () {
  7965. return this._lastSecAverage;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(PerfCounter.prototype, "current", {
  7971. /**
  7972. * Returns the current value
  7973. */
  7974. get: function () {
  7975. return this._current;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(PerfCounter.prototype, "total", {
  7981. get: function () {
  7982. return this._totalAccumulated;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(PerfCounter.prototype, "count", {
  7988. get: function () {
  7989. return this._totalValueCount;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. /**
  7995. * Call this method to start monitoring a new frame.
  7996. * 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.
  7997. */
  7998. PerfCounter.prototype.fetchNewFrame = function () {
  7999. this._totalValueCount++;
  8000. this._current = 0;
  8001. this._lastSecValueCount++;
  8002. };
  8003. /**
  8004. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8005. * @param newCount the count value to add to the monitored count
  8006. * @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.
  8007. */
  8008. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8009. if (!PerfCounter.Enabled) {
  8010. return;
  8011. }
  8012. this._current += newCount;
  8013. if (fetchResult) {
  8014. this._fetchResult();
  8015. }
  8016. };
  8017. /**
  8018. * Start monitoring this performance counter
  8019. */
  8020. PerfCounter.prototype.beginMonitoring = function () {
  8021. if (!PerfCounter.Enabled) {
  8022. return;
  8023. }
  8024. this._startMonitoringTime = Tools.Now;
  8025. };
  8026. /**
  8027. * Compute the time lapsed since the previous beginMonitoring() call.
  8028. * @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
  8029. */
  8030. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8031. if (newFrame === void 0) { newFrame = true; }
  8032. if (!PerfCounter.Enabled) {
  8033. return;
  8034. }
  8035. if (newFrame) {
  8036. this.fetchNewFrame();
  8037. }
  8038. var currentTime = Tools.Now;
  8039. this._current = currentTime - this._startMonitoringTime;
  8040. if (newFrame) {
  8041. this._fetchResult();
  8042. }
  8043. };
  8044. PerfCounter.prototype._fetchResult = function () {
  8045. this._totalAccumulated += this._current;
  8046. this._lastSecAccumulated += this._current;
  8047. // Min/Max update
  8048. this._min = Math.min(this._min, this._current);
  8049. this._max = Math.max(this._max, this._current);
  8050. this._average = this._totalAccumulated / this._totalValueCount;
  8051. // Reset last sec?
  8052. var now = Tools.Now;
  8053. if ((now - this._lastSecTime) > 1000) {
  8054. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8055. this._lastSecTime = now;
  8056. this._lastSecAccumulated = 0;
  8057. this._lastSecValueCount = 0;
  8058. }
  8059. };
  8060. PerfCounter.Enabled = true;
  8061. return PerfCounter;
  8062. }());
  8063. BABYLON.PerfCounter = PerfCounter;
  8064. /**
  8065. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8066. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8067. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8068. * @param name The name of the class, case should be preserved
  8069. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8070. */
  8071. function className(name, module) {
  8072. return function (target) {
  8073. target["__bjsclassName__"] = name;
  8074. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8075. };
  8076. }
  8077. BABYLON.className = className;
  8078. /**
  8079. * An implementation of a loop for asynchronous functions.
  8080. */
  8081. var AsyncLoop = /** @class */ (function () {
  8082. /**
  8083. * Constroctor.
  8084. * @param iterations the number of iterations.
  8085. * @param _fn the function to run each iteration
  8086. * @param _successCallback the callback that will be called upon succesful execution
  8087. * @param offset starting offset.
  8088. */
  8089. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8090. if (offset === void 0) { offset = 0; }
  8091. this.iterations = iterations;
  8092. this._fn = _fn;
  8093. this._successCallback = _successCallback;
  8094. this.index = offset - 1;
  8095. this._done = false;
  8096. }
  8097. /**
  8098. * Execute the next iteration. Must be called after the last iteration was finished.
  8099. */
  8100. AsyncLoop.prototype.executeNext = function () {
  8101. if (!this._done) {
  8102. if (this.index + 1 < this.iterations) {
  8103. ++this.index;
  8104. this._fn(this);
  8105. }
  8106. else {
  8107. this.breakLoop();
  8108. }
  8109. }
  8110. };
  8111. /**
  8112. * Break the loop and run the success callback.
  8113. */
  8114. AsyncLoop.prototype.breakLoop = function () {
  8115. this._done = true;
  8116. this._successCallback();
  8117. };
  8118. /**
  8119. * Helper function
  8120. */
  8121. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8122. if (offset === void 0) { offset = 0; }
  8123. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8124. loop.executeNext();
  8125. return loop;
  8126. };
  8127. /**
  8128. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8129. * @param iterations total number of iterations
  8130. * @param syncedIterations number of synchronous iterations in each async iteration.
  8131. * @param fn the function to call each iteration.
  8132. * @param callback a success call back that will be called when iterating stops.
  8133. * @param breakFunction a break condition (optional)
  8134. * @param timeout timeout settings for the setTimeout function. default - 0.
  8135. * @constructor
  8136. */
  8137. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8138. if (timeout === void 0) { timeout = 0; }
  8139. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8140. if (breakFunction && breakFunction())
  8141. loop.breakLoop();
  8142. else {
  8143. setTimeout(function () {
  8144. for (var i = 0; i < syncedIterations; ++i) {
  8145. var iteration = (loop.index * syncedIterations) + i;
  8146. if (iteration >= iterations)
  8147. break;
  8148. fn(iteration);
  8149. if (breakFunction && breakFunction()) {
  8150. loop.breakLoop();
  8151. break;
  8152. }
  8153. }
  8154. loop.executeNext();
  8155. }, timeout);
  8156. }
  8157. }, callback);
  8158. };
  8159. return AsyncLoop;
  8160. }());
  8161. BABYLON.AsyncLoop = AsyncLoop;
  8162. })(BABYLON || (BABYLON = {}));
  8163. //# sourceMappingURL=babylon.tools.js.map
  8164. var BABYLON;
  8165. (function (BABYLON) {
  8166. var _AlphaState = /** @class */ (function () {
  8167. /**
  8168. * Initializes the state.
  8169. */
  8170. function _AlphaState() {
  8171. this._isAlphaBlendDirty = false;
  8172. this._isBlendFunctionParametersDirty = false;
  8173. this._isBlendEquationParametersDirty = false;
  8174. this._isBlendConstantsDirty = false;
  8175. this._alphaBlend = false;
  8176. this._blendFunctionParameters = new Array(4);
  8177. this._blendEquationParameters = new Array(2);
  8178. this._blendConstants = new Array(4);
  8179. this.reset();
  8180. }
  8181. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8182. get: function () {
  8183. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8189. get: function () {
  8190. return this._alphaBlend;
  8191. },
  8192. set: function (value) {
  8193. if (this._alphaBlend === value) {
  8194. return;
  8195. }
  8196. this._alphaBlend = value;
  8197. this._isAlphaBlendDirty = true;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8203. if (this._blendConstants[0] === r &&
  8204. this._blendConstants[1] === g &&
  8205. this._blendConstants[2] === b &&
  8206. this._blendConstants[3] === a) {
  8207. return;
  8208. }
  8209. this._blendConstants[0] = r;
  8210. this._blendConstants[1] = g;
  8211. this._blendConstants[2] = b;
  8212. this._blendConstants[3] = a;
  8213. this._isBlendConstantsDirty = true;
  8214. };
  8215. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8216. if (this._blendFunctionParameters[0] === value0 &&
  8217. this._blendFunctionParameters[1] === value1 &&
  8218. this._blendFunctionParameters[2] === value2 &&
  8219. this._blendFunctionParameters[3] === value3) {
  8220. return;
  8221. }
  8222. this._blendFunctionParameters[0] = value0;
  8223. this._blendFunctionParameters[1] = value1;
  8224. this._blendFunctionParameters[2] = value2;
  8225. this._blendFunctionParameters[3] = value3;
  8226. this._isBlendFunctionParametersDirty = true;
  8227. };
  8228. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8229. if (this._blendEquationParameters[0] === rgb &&
  8230. this._blendEquationParameters[1] === alpha) {
  8231. return;
  8232. }
  8233. this._blendEquationParameters[0] = rgb;
  8234. this._blendEquationParameters[1] = alpha;
  8235. this._isBlendEquationParametersDirty = true;
  8236. };
  8237. _AlphaState.prototype.reset = function () {
  8238. this._alphaBlend = false;
  8239. this._blendFunctionParameters[0] = null;
  8240. this._blendFunctionParameters[1] = null;
  8241. this._blendFunctionParameters[2] = null;
  8242. this._blendFunctionParameters[3] = null;
  8243. this._blendEquationParameters[0] = null;
  8244. this._blendEquationParameters[1] = null;
  8245. this._blendConstants[0] = null;
  8246. this._blendConstants[1] = null;
  8247. this._blendConstants[2] = null;
  8248. this._blendConstants[3] = null;
  8249. this._isAlphaBlendDirty = true;
  8250. this._isBlendFunctionParametersDirty = false;
  8251. this._isBlendEquationParametersDirty = false;
  8252. this._isBlendConstantsDirty = false;
  8253. };
  8254. _AlphaState.prototype.apply = function (gl) {
  8255. if (!this.isDirty) {
  8256. return;
  8257. }
  8258. // Alpha blend
  8259. if (this._isAlphaBlendDirty) {
  8260. if (this._alphaBlend) {
  8261. gl.enable(gl.BLEND);
  8262. }
  8263. else {
  8264. gl.disable(gl.BLEND);
  8265. }
  8266. this._isAlphaBlendDirty = false;
  8267. }
  8268. // Alpha function
  8269. if (this._isBlendFunctionParametersDirty) {
  8270. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8271. this._isBlendFunctionParametersDirty = false;
  8272. }
  8273. // Alpha equation
  8274. if (this._isBlendEquationParametersDirty) {
  8275. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8276. this._isBlendEquationParametersDirty = false;
  8277. }
  8278. // Constants
  8279. if (this._isBlendConstantsDirty) {
  8280. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8281. this._isBlendConstantsDirty = false;
  8282. }
  8283. };
  8284. return _AlphaState;
  8285. }());
  8286. BABYLON._AlphaState = _AlphaState;
  8287. })(BABYLON || (BABYLON = {}));
  8288. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. var _DepthCullingState = /** @class */ (function () {
  8292. /**
  8293. * Initializes the state.
  8294. */
  8295. function _DepthCullingState() {
  8296. this._isDepthTestDirty = false;
  8297. this._isDepthMaskDirty = false;
  8298. this._isDepthFuncDirty = false;
  8299. this._isCullFaceDirty = false;
  8300. this._isCullDirty = false;
  8301. this._isZOffsetDirty = false;
  8302. this._isFrontFaceDirty = false;
  8303. this.reset();
  8304. }
  8305. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8306. get: function () {
  8307. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8313. get: function () {
  8314. return this._zOffset;
  8315. },
  8316. set: function (value) {
  8317. if (this._zOffset === value) {
  8318. return;
  8319. }
  8320. this._zOffset = value;
  8321. this._isZOffsetDirty = true;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8327. get: function () {
  8328. return this._cullFace;
  8329. },
  8330. set: function (value) {
  8331. if (this._cullFace === value) {
  8332. return;
  8333. }
  8334. this._cullFace = value;
  8335. this._isCullFaceDirty = true;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8341. get: function () {
  8342. return this._cull;
  8343. },
  8344. set: function (value) {
  8345. if (this._cull === value) {
  8346. return;
  8347. }
  8348. this._cull = value;
  8349. this._isCullDirty = true;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8355. get: function () {
  8356. return this._depthFunc;
  8357. },
  8358. set: function (value) {
  8359. if (this._depthFunc === value) {
  8360. return;
  8361. }
  8362. this._depthFunc = value;
  8363. this._isDepthFuncDirty = true;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8369. get: function () {
  8370. return this._depthMask;
  8371. },
  8372. set: function (value) {
  8373. if (this._depthMask === value) {
  8374. return;
  8375. }
  8376. this._depthMask = value;
  8377. this._isDepthMaskDirty = true;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8383. get: function () {
  8384. return this._depthTest;
  8385. },
  8386. set: function (value) {
  8387. if (this._depthTest === value) {
  8388. return;
  8389. }
  8390. this._depthTest = value;
  8391. this._isDepthTestDirty = true;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8397. get: function () {
  8398. return this._frontFace;
  8399. },
  8400. set: function (value) {
  8401. if (this._frontFace === value) {
  8402. return;
  8403. }
  8404. this._frontFace = value;
  8405. this._isFrontFaceDirty = true;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. _DepthCullingState.prototype.reset = function () {
  8411. this._depthMask = true;
  8412. this._depthTest = true;
  8413. this._depthFunc = null;
  8414. this._cullFace = null;
  8415. this._cull = null;
  8416. this._zOffset = 0;
  8417. this._frontFace = null;
  8418. this._isDepthTestDirty = true;
  8419. this._isDepthMaskDirty = true;
  8420. this._isDepthFuncDirty = false;
  8421. this._isCullFaceDirty = false;
  8422. this._isCullDirty = false;
  8423. this._isZOffsetDirty = false;
  8424. this._isFrontFaceDirty = false;
  8425. };
  8426. _DepthCullingState.prototype.apply = function (gl) {
  8427. if (!this.isDirty) {
  8428. return;
  8429. }
  8430. // Cull
  8431. if (this._isCullDirty) {
  8432. if (this.cull) {
  8433. gl.enable(gl.CULL_FACE);
  8434. }
  8435. else {
  8436. gl.disable(gl.CULL_FACE);
  8437. }
  8438. this._isCullDirty = false;
  8439. }
  8440. // Cull face
  8441. if (this._isCullFaceDirty) {
  8442. gl.cullFace(this.cullFace);
  8443. this._isCullFaceDirty = false;
  8444. }
  8445. // Depth mask
  8446. if (this._isDepthMaskDirty) {
  8447. gl.depthMask(this.depthMask);
  8448. this._isDepthMaskDirty = false;
  8449. }
  8450. // Depth test
  8451. if (this._isDepthTestDirty) {
  8452. if (this.depthTest) {
  8453. gl.enable(gl.DEPTH_TEST);
  8454. }
  8455. else {
  8456. gl.disable(gl.DEPTH_TEST);
  8457. }
  8458. this._isDepthTestDirty = false;
  8459. }
  8460. // Depth func
  8461. if (this._isDepthFuncDirty) {
  8462. gl.depthFunc(this.depthFunc);
  8463. this._isDepthFuncDirty = false;
  8464. }
  8465. // zOffset
  8466. if (this._isZOffsetDirty) {
  8467. if (this.zOffset) {
  8468. gl.enable(gl.POLYGON_OFFSET_FILL);
  8469. gl.polygonOffset(this.zOffset, 0);
  8470. }
  8471. else {
  8472. gl.disable(gl.POLYGON_OFFSET_FILL);
  8473. }
  8474. this._isZOffsetDirty = false;
  8475. }
  8476. // Front face
  8477. if (this._isFrontFaceDirty) {
  8478. gl.frontFace(this.frontFace);
  8479. this._isFrontFaceDirty = false;
  8480. }
  8481. };
  8482. return _DepthCullingState;
  8483. }());
  8484. BABYLON._DepthCullingState = _DepthCullingState;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.depthCullingState.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. var _StencilState = /** @class */ (function () {
  8490. function _StencilState() {
  8491. this._isStencilTestDirty = false;
  8492. this._isStencilMaskDirty = false;
  8493. this._isStencilFuncDirty = false;
  8494. this._isStencilOpDirty = false;
  8495. this.reset();
  8496. }
  8497. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8498. get: function () {
  8499. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8505. get: function () {
  8506. return this._stencilFunc;
  8507. },
  8508. set: function (value) {
  8509. if (this._stencilFunc === value) {
  8510. return;
  8511. }
  8512. this._stencilFunc = value;
  8513. this._isStencilFuncDirty = true;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8519. get: function () {
  8520. return this._stencilFuncRef;
  8521. },
  8522. set: function (value) {
  8523. if (this._stencilFuncRef === value) {
  8524. return;
  8525. }
  8526. this._stencilFuncRef = value;
  8527. this._isStencilFuncDirty = true;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8533. get: function () {
  8534. return this._stencilFuncMask;
  8535. },
  8536. set: function (value) {
  8537. if (this._stencilFuncMask === value) {
  8538. return;
  8539. }
  8540. this._stencilFuncMask = value;
  8541. this._isStencilFuncDirty = true;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8547. get: function () {
  8548. return this._stencilOpStencilFail;
  8549. },
  8550. set: function (value) {
  8551. if (this._stencilOpStencilFail === value) {
  8552. return;
  8553. }
  8554. this._stencilOpStencilFail = value;
  8555. this._isStencilOpDirty = true;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8561. get: function () {
  8562. return this._stencilOpDepthFail;
  8563. },
  8564. set: function (value) {
  8565. if (this._stencilOpDepthFail === value) {
  8566. return;
  8567. }
  8568. this._stencilOpDepthFail = value;
  8569. this._isStencilOpDirty = true;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8575. get: function () {
  8576. return this._stencilOpStencilDepthPass;
  8577. },
  8578. set: function (value) {
  8579. if (this._stencilOpStencilDepthPass === value) {
  8580. return;
  8581. }
  8582. this._stencilOpStencilDepthPass = value;
  8583. this._isStencilOpDirty = true;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8589. get: function () {
  8590. return this._stencilMask;
  8591. },
  8592. set: function (value) {
  8593. if (this._stencilMask === value) {
  8594. return;
  8595. }
  8596. this._stencilMask = value;
  8597. this._isStencilMaskDirty = true;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8603. get: function () {
  8604. return this._stencilTest;
  8605. },
  8606. set: function (value) {
  8607. if (this._stencilTest === value) {
  8608. return;
  8609. }
  8610. this._stencilTest = value;
  8611. this._isStencilTestDirty = true;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. _StencilState.prototype.reset = function () {
  8617. this._stencilTest = false;
  8618. this._stencilMask = 0xFF;
  8619. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8620. this._stencilFuncRef = 1;
  8621. this._stencilFuncMask = 0xFF;
  8622. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8623. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8624. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8625. this._isStencilTestDirty = true;
  8626. this._isStencilMaskDirty = true;
  8627. this._isStencilFuncDirty = true;
  8628. this._isStencilOpDirty = true;
  8629. };
  8630. _StencilState.prototype.apply = function (gl) {
  8631. if (!this.isDirty) {
  8632. return;
  8633. }
  8634. // Stencil test
  8635. if (this._isStencilTestDirty) {
  8636. if (this.stencilTest) {
  8637. gl.enable(gl.STENCIL_TEST);
  8638. }
  8639. else {
  8640. gl.disable(gl.STENCIL_TEST);
  8641. }
  8642. this._isStencilTestDirty = false;
  8643. }
  8644. // Stencil mask
  8645. if (this._isStencilMaskDirty) {
  8646. gl.stencilMask(this.stencilMask);
  8647. this._isStencilMaskDirty = false;
  8648. }
  8649. // Stencil func
  8650. if (this._isStencilFuncDirty) {
  8651. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8652. this._isStencilFuncDirty = false;
  8653. }
  8654. // Stencil op
  8655. if (this._isStencilOpDirty) {
  8656. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8657. this._isStencilOpDirty = false;
  8658. }
  8659. };
  8660. return _StencilState;
  8661. }());
  8662. BABYLON._StencilState = _StencilState;
  8663. })(BABYLON || (BABYLON = {}));
  8664. //# sourceMappingURL=babylon.stencilState.js.map
  8665. var BABYLON;
  8666. (function (BABYLON) {
  8667. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8668. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8669. };
  8670. var compileRawShader = function (gl, source, type) {
  8671. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8672. gl.shaderSource(shader, source);
  8673. gl.compileShader(shader);
  8674. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8675. var log = gl.getShaderInfoLog(shader);
  8676. if (log) {
  8677. throw new Error(log);
  8678. }
  8679. }
  8680. if (!shader) {
  8681. throw new Error("Something went wrong while compile the shader.");
  8682. }
  8683. return shader;
  8684. };
  8685. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8686. var magFilter = gl.NEAREST;
  8687. var minFilter = gl.NEAREST;
  8688. switch (samplingMode) {
  8689. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8690. magFilter = gl.LINEAR;
  8691. if (generateMipMaps) {
  8692. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8693. }
  8694. else {
  8695. minFilter = gl.LINEAR;
  8696. }
  8697. break;
  8698. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8699. magFilter = gl.LINEAR;
  8700. if (generateMipMaps) {
  8701. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8702. }
  8703. else {
  8704. minFilter = gl.LINEAR;
  8705. }
  8706. break;
  8707. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8708. magFilter = gl.NEAREST;
  8709. if (generateMipMaps) {
  8710. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8711. }
  8712. else {
  8713. minFilter = gl.NEAREST;
  8714. }
  8715. break;
  8716. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8717. magFilter = gl.NEAREST;
  8718. if (generateMipMaps) {
  8719. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8720. }
  8721. else {
  8722. minFilter = gl.NEAREST;
  8723. }
  8724. break;
  8725. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8726. magFilter = gl.NEAREST;
  8727. if (generateMipMaps) {
  8728. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8729. }
  8730. else {
  8731. minFilter = gl.LINEAR;
  8732. }
  8733. break;
  8734. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8735. magFilter = gl.NEAREST;
  8736. if (generateMipMaps) {
  8737. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8738. }
  8739. else {
  8740. minFilter = gl.LINEAR;
  8741. }
  8742. break;
  8743. case BABYLON.Texture.NEAREST_LINEAR:
  8744. magFilter = gl.NEAREST;
  8745. minFilter = gl.LINEAR;
  8746. break;
  8747. case BABYLON.Texture.NEAREST_NEAREST:
  8748. magFilter = gl.NEAREST;
  8749. minFilter = gl.NEAREST;
  8750. break;
  8751. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8752. magFilter = gl.LINEAR;
  8753. if (generateMipMaps) {
  8754. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8755. }
  8756. else {
  8757. minFilter = gl.NEAREST;
  8758. }
  8759. break;
  8760. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8761. magFilter = gl.LINEAR;
  8762. if (generateMipMaps) {
  8763. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8764. }
  8765. else {
  8766. minFilter = gl.NEAREST;
  8767. }
  8768. break;
  8769. case BABYLON.Texture.LINEAR_LINEAR:
  8770. magFilter = gl.LINEAR;
  8771. minFilter = gl.LINEAR;
  8772. break;
  8773. case BABYLON.Texture.LINEAR_NEAREST:
  8774. magFilter = gl.LINEAR;
  8775. minFilter = gl.NEAREST;
  8776. break;
  8777. }
  8778. return {
  8779. min: minFilter,
  8780. mag: magFilter
  8781. };
  8782. };
  8783. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8784. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8785. var img;
  8786. var onload = function () {
  8787. loadedImages[index] = img;
  8788. loadedImages._internalCount++;
  8789. if (scene) {
  8790. scene._removePendingData(img);
  8791. }
  8792. if (loadedImages._internalCount === 6) {
  8793. onfinish(loadedImages);
  8794. }
  8795. };
  8796. var onerror = function (message, exception) {
  8797. if (scene) {
  8798. scene._removePendingData(img);
  8799. }
  8800. if (onErrorCallBack) {
  8801. onErrorCallBack(message, exception);
  8802. }
  8803. };
  8804. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8805. if (scene) {
  8806. scene._addPendingData(img);
  8807. }
  8808. };
  8809. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8810. if (onError === void 0) { onError = null; }
  8811. var loadedImages = [];
  8812. loadedImages._internalCount = 0;
  8813. for (var index = 0; index < 6; index++) {
  8814. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8815. }
  8816. };
  8817. var BufferPointer = /** @class */ (function () {
  8818. function BufferPointer() {
  8819. }
  8820. return BufferPointer;
  8821. }());
  8822. var InstancingAttributeInfo = /** @class */ (function () {
  8823. function InstancingAttributeInfo() {
  8824. }
  8825. return InstancingAttributeInfo;
  8826. }());
  8827. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8828. /**
  8829. * Define options used to create a render target texture
  8830. */
  8831. var RenderTargetCreationOptions = /** @class */ (function () {
  8832. function RenderTargetCreationOptions() {
  8833. }
  8834. return RenderTargetCreationOptions;
  8835. }());
  8836. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8837. /**
  8838. * Regroup several parameters relative to the browser in use
  8839. */
  8840. var EngineCapabilities = /** @class */ (function () {
  8841. function EngineCapabilities() {
  8842. }
  8843. return EngineCapabilities;
  8844. }());
  8845. BABYLON.EngineCapabilities = EngineCapabilities;
  8846. /**
  8847. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8848. */
  8849. var Engine = /** @class */ (function () {
  8850. /**
  8851. * @constructor
  8852. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8853. * @param {boolean} [antialias] - enable antialias
  8854. * @param options - further options to be sent to the getContext function
  8855. */
  8856. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8857. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8858. var _this = this;
  8859. // Public members
  8860. this.forcePOTTextures = false;
  8861. this.isFullscreen = false;
  8862. this.isPointerLock = false;
  8863. this.cullBackFaces = true;
  8864. this.renderEvenInBackground = true;
  8865. this.preventCacheWipeBetweenFrames = false;
  8866. // To enable/disable IDB support and avoid XHR on .manifest
  8867. this.enableOfflineSupport = false;
  8868. this.scenes = new Array();
  8869. this.postProcesses = new Array();
  8870. // Observables
  8871. /**
  8872. * Observable event triggered each time the rendering canvas is resized
  8873. */
  8874. this.onResizeObservable = new BABYLON.Observable();
  8875. /**
  8876. * Observable event triggered each time the canvas loses focus
  8877. */
  8878. this.onCanvasBlurObservable = new BABYLON.Observable();
  8879. /**
  8880. * Observable event triggered each time the canvas gains focus
  8881. */
  8882. this.onCanvasFocusObservable = new BABYLON.Observable();
  8883. /**
  8884. * Observable event triggered each time the canvas receives pointerout event
  8885. */
  8886. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8887. /**
  8888. * Observable event triggered before each texture is initialized
  8889. */
  8890. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8891. //WebVR
  8892. this._vrDisplay = undefined;
  8893. this._vrSupported = false;
  8894. this._vrExclusivePointerMode = false;
  8895. // Uniform buffers list
  8896. this.disableUniformBuffers = false;
  8897. this._uniformBuffers = new Array();
  8898. // Observables
  8899. /**
  8900. * Observable raised when the engine begins a new frame
  8901. */
  8902. this.onBeginFrameObservable = new BABYLON.Observable();
  8903. /**
  8904. * Observable raised when the engine ends the current frame
  8905. */
  8906. this.onEndFrameObservable = new BABYLON.Observable();
  8907. /**
  8908. * Observable raised when the engine is about to compile a shader
  8909. */
  8910. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8911. /**
  8912. * Observable raised when the engine has jsut compiled a shader
  8913. */
  8914. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8915. this._windowIsBackground = false;
  8916. this._webGLVersion = 1.0;
  8917. this._badOS = false;
  8918. this._badDesktopOS = false;
  8919. /**
  8920. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8921. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8922. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8923. */
  8924. this.disableTextureBindingOptimization = false;
  8925. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8926. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8927. this.onVRRequestPresentStart = new BABYLON.Observable();
  8928. this._colorWrite = true;
  8929. this._drawCalls = new BABYLON.PerfCounter();
  8930. this._textureCollisions = new BABYLON.PerfCounter();
  8931. this._renderingQueueLaunched = false;
  8932. this._activeRenderLoops = new Array();
  8933. // Deterministic lockstepMaxSteps
  8934. this._deterministicLockstep = false;
  8935. this._lockstepMaxSteps = 4;
  8936. // Lost context
  8937. this.onContextLostObservable = new BABYLON.Observable();
  8938. this.onContextRestoredObservable = new BABYLON.Observable();
  8939. this._contextWasLost = false;
  8940. this._doNotHandleContextLost = false;
  8941. // FPS
  8942. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8943. this._fps = 60;
  8944. this._deltaTime = 0;
  8945. /**
  8946. * Turn this value on if you want to pause FPS computation when in background
  8947. */
  8948. this.disablePerformanceMonitorInBackground = false;
  8949. // States
  8950. this._depthCullingState = new BABYLON._DepthCullingState();
  8951. this._stencilState = new BABYLON._StencilState();
  8952. this._alphaState = new BABYLON._AlphaState();
  8953. this._alphaMode = Engine.ALPHA_DISABLE;
  8954. // Cache
  8955. this._internalTexturesCache = new Array();
  8956. this._boundTexturesCache = {};
  8957. this._boundTexturesStack = new Array();
  8958. this._compiledEffects = {};
  8959. this._vertexAttribArraysEnabled = [];
  8960. this._uintIndicesCurrentlySet = false;
  8961. this._currentBoundBuffer = new Array();
  8962. this._currentBufferPointers = new Array();
  8963. this._currentInstanceLocations = new Array();
  8964. this._currentInstanceBuffers = new Array();
  8965. this._vaoRecordInProgress = false;
  8966. this._mustWipeVertexAttributes = false;
  8967. this._nextFreeTextureSlots = new Array();
  8968. this._maxSimultaneousTextures = 0;
  8969. this._activeRequests = new Array();
  8970. // Hardware supported Compressed Textures
  8971. this._texturesSupported = new Array();
  8972. this._onVRFullScreenTriggered = function () {
  8973. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8974. //get the old size before we change
  8975. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8976. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8977. //get the width and height, change the render size
  8978. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8979. _this.setHardwareScalingLevel(1);
  8980. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8981. }
  8982. else {
  8983. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8984. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8985. }
  8986. };
  8987. this._boundUniforms = {};
  8988. var canvas = null;
  8989. Engine.Instances.push(this);
  8990. if (!canvasOrContext) {
  8991. return;
  8992. }
  8993. options = options || {};
  8994. if (canvasOrContext.getContext) {
  8995. canvas = canvasOrContext;
  8996. this._renderingCanvas = canvas;
  8997. if (antialias != null) {
  8998. options.antialias = antialias;
  8999. }
  9000. if (options.deterministicLockstep === undefined) {
  9001. options.deterministicLockstep = false;
  9002. }
  9003. if (options.lockstepMaxSteps === undefined) {
  9004. options.lockstepMaxSteps = 4;
  9005. }
  9006. if (options.preserveDrawingBuffer === undefined) {
  9007. options.preserveDrawingBuffer = false;
  9008. }
  9009. if (options.audioEngine === undefined) {
  9010. options.audioEngine = true;
  9011. }
  9012. if (options.stencil === undefined) {
  9013. options.stencil = true;
  9014. }
  9015. this._deterministicLockstep = options.deterministicLockstep;
  9016. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9017. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9018. // Exceptions
  9019. if (navigator && navigator.userAgent) {
  9020. var ua = navigator.userAgent;
  9021. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9022. var exception = _a[_i];
  9023. var key = exception.key;
  9024. var targets = exception.targets;
  9025. if (ua.indexOf(key) > -1) {
  9026. if (exception.capture && exception.captureConstraint) {
  9027. var capture = exception.capture;
  9028. var constraint = exception.captureConstraint;
  9029. var regex = new RegExp(capture);
  9030. var matches = regex.exec(ua);
  9031. if (matches && matches.length > 0) {
  9032. var capturedValue = parseInt(matches[matches.length - 1]);
  9033. if (capturedValue >= constraint) {
  9034. continue;
  9035. }
  9036. }
  9037. }
  9038. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9039. var target = targets_1[_b];
  9040. switch (target) {
  9041. case "uniformBuffer":
  9042. this.disableUniformBuffers = true;
  9043. break;
  9044. case "textureBindingOptimization":
  9045. this.disableTextureBindingOptimization = true;
  9046. break;
  9047. }
  9048. }
  9049. break;
  9050. }
  9051. }
  9052. }
  9053. // GL
  9054. if (!options.disableWebGL2Support) {
  9055. try {
  9056. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9057. if (this._gl) {
  9058. this._webGLVersion = 2.0;
  9059. }
  9060. }
  9061. catch (e) {
  9062. // Do nothing
  9063. }
  9064. }
  9065. if (!this._gl) {
  9066. if (!canvas) {
  9067. throw new Error("The provided canvas is null or undefined.");
  9068. }
  9069. try {
  9070. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9071. }
  9072. catch (e) {
  9073. throw new Error("WebGL not supported");
  9074. }
  9075. }
  9076. if (!this._gl) {
  9077. throw new Error("WebGL not supported");
  9078. }
  9079. this._onCanvasFocus = function () {
  9080. _this.onCanvasFocusObservable.notifyObservers(_this);
  9081. };
  9082. this._onCanvasBlur = function () {
  9083. _this.onCanvasBlurObservable.notifyObservers(_this);
  9084. };
  9085. canvas.addEventListener("focus", this._onCanvasFocus);
  9086. canvas.addEventListener("blur", this._onCanvasBlur);
  9087. this._onBlur = function () {
  9088. if (_this.disablePerformanceMonitorInBackground) {
  9089. _this._performanceMonitor.disable();
  9090. }
  9091. _this._windowIsBackground = true;
  9092. };
  9093. this._onFocus = function () {
  9094. if (_this.disablePerformanceMonitorInBackground) {
  9095. _this._performanceMonitor.enable();
  9096. }
  9097. _this._windowIsBackground = false;
  9098. };
  9099. this._onCanvasPointerOut = function () {
  9100. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9101. };
  9102. window.addEventListener("blur", this._onBlur);
  9103. window.addEventListener("focus", this._onFocus);
  9104. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9105. // Context lost
  9106. if (!this._doNotHandleContextLost) {
  9107. this._onContextLost = function (evt) {
  9108. evt.preventDefault();
  9109. _this._contextWasLost = true;
  9110. BABYLON.Tools.Warn("WebGL context lost.");
  9111. _this.onContextLostObservable.notifyObservers(_this);
  9112. };
  9113. this._onContextRestored = function (evt) {
  9114. // Adding a timeout to avoid race condition at browser level
  9115. setTimeout(function () {
  9116. // Rebuild gl context
  9117. _this._initGLContext();
  9118. // Rebuild effects
  9119. _this._rebuildEffects();
  9120. // Rebuild textures
  9121. _this._rebuildInternalTextures();
  9122. // Rebuild buffers
  9123. _this._rebuildBuffers();
  9124. // Cache
  9125. _this.wipeCaches(true);
  9126. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9127. _this.onContextRestoredObservable.notifyObservers(_this);
  9128. _this._contextWasLost = false;
  9129. }, 0);
  9130. };
  9131. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9132. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9133. }
  9134. }
  9135. else {
  9136. this._gl = canvasOrContext;
  9137. this._renderingCanvas = this._gl.canvas;
  9138. if (this._gl.renderbufferStorageMultisample) {
  9139. this._webGLVersion = 2.0;
  9140. }
  9141. options.stencil = this._gl.getContextAttributes().stencil;
  9142. }
  9143. // Viewport
  9144. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9145. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9146. this.resize();
  9147. this._isStencilEnable = options.stencil ? true : false;
  9148. this._initGLContext();
  9149. if (canvas) {
  9150. // Fullscreen
  9151. this._onFullscreenChange = function () {
  9152. if (document.fullscreen !== undefined) {
  9153. _this.isFullscreen = document.fullscreen;
  9154. }
  9155. else if (document.mozFullScreen !== undefined) {
  9156. _this.isFullscreen = document.mozFullScreen;
  9157. }
  9158. else if (document.webkitIsFullScreen !== undefined) {
  9159. _this.isFullscreen = document.webkitIsFullScreen;
  9160. }
  9161. else if (document.msIsFullScreen !== undefined) {
  9162. _this.isFullscreen = document.msIsFullScreen;
  9163. }
  9164. // Pointer lock
  9165. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9166. canvas.requestPointerLock = canvas.requestPointerLock ||
  9167. canvas.msRequestPointerLock ||
  9168. canvas.mozRequestPointerLock ||
  9169. canvas.webkitRequestPointerLock;
  9170. if (canvas.requestPointerLock) {
  9171. canvas.requestPointerLock();
  9172. }
  9173. }
  9174. };
  9175. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9176. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9177. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9178. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9179. // Pointer lock
  9180. this._onPointerLockChange = function () {
  9181. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9182. document.webkitPointerLockElement === canvas ||
  9183. document.msPointerLockElement === canvas ||
  9184. document.pointerLockElement === canvas);
  9185. };
  9186. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9187. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9188. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9189. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9190. this._onVRDisplayPointerRestricted = function () {
  9191. if (canvas) {
  9192. canvas.requestPointerLock();
  9193. }
  9194. };
  9195. this._onVRDisplayPointerUnrestricted = function () {
  9196. document.exitPointerLock();
  9197. };
  9198. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9199. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9200. }
  9201. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9202. Engine.audioEngine = new BABYLON.AudioEngine();
  9203. }
  9204. // Prepare buffer pointers
  9205. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9206. this._currentBufferPointers[i] = new BufferPointer();
  9207. }
  9208. // Load WebVR Devices
  9209. if (options.autoEnableWebVR) {
  9210. this.initWebVR();
  9211. }
  9212. // Detect if we are running on a faulty buggy OS.
  9213. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9214. // Detect if we are running on a faulty buggy desktop OS.
  9215. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9216. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9217. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9218. }
  9219. Object.defineProperty(Engine, "LastCreatedEngine", {
  9220. get: function () {
  9221. if (Engine.Instances.length === 0) {
  9222. return null;
  9223. }
  9224. return Engine.Instances[Engine.Instances.length - 1];
  9225. },
  9226. enumerable: true,
  9227. configurable: true
  9228. });
  9229. Object.defineProperty(Engine, "LastCreatedScene", {
  9230. get: function () {
  9231. var lastCreatedEngine = Engine.LastCreatedEngine;
  9232. if (!lastCreatedEngine) {
  9233. return null;
  9234. }
  9235. if (lastCreatedEngine.scenes.length === 0) {
  9236. return null;
  9237. }
  9238. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9239. },
  9240. enumerable: true,
  9241. configurable: true
  9242. });
  9243. /**
  9244. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9245. */
  9246. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9247. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9248. var engine = Engine.Instances[engineIndex];
  9249. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9250. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9251. }
  9252. }
  9253. };
  9254. Object.defineProperty(Engine, "NEVER", {
  9255. get: function () {
  9256. return Engine._NEVER;
  9257. },
  9258. enumerable: true,
  9259. configurable: true
  9260. });
  9261. Object.defineProperty(Engine, "ALWAYS", {
  9262. get: function () {
  9263. return Engine._ALWAYS;
  9264. },
  9265. enumerable: true,
  9266. configurable: true
  9267. });
  9268. Object.defineProperty(Engine, "LESS", {
  9269. get: function () {
  9270. return Engine._LESS;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(Engine, "EQUAL", {
  9276. get: function () {
  9277. return Engine._EQUAL;
  9278. },
  9279. enumerable: true,
  9280. configurable: true
  9281. });
  9282. Object.defineProperty(Engine, "LEQUAL", {
  9283. get: function () {
  9284. return Engine._LEQUAL;
  9285. },
  9286. enumerable: true,
  9287. configurable: true
  9288. });
  9289. Object.defineProperty(Engine, "GREATER", {
  9290. get: function () {
  9291. return Engine._GREATER;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(Engine, "GEQUAL", {
  9297. get: function () {
  9298. return Engine._GEQUAL;
  9299. },
  9300. enumerable: true,
  9301. configurable: true
  9302. });
  9303. Object.defineProperty(Engine, "NOTEQUAL", {
  9304. get: function () {
  9305. return Engine._NOTEQUAL;
  9306. },
  9307. enumerable: true,
  9308. configurable: true
  9309. });
  9310. Object.defineProperty(Engine, "KEEP", {
  9311. get: function () {
  9312. return Engine._KEEP;
  9313. },
  9314. enumerable: true,
  9315. configurable: true
  9316. });
  9317. Object.defineProperty(Engine, "REPLACE", {
  9318. get: function () {
  9319. return Engine._REPLACE;
  9320. },
  9321. enumerable: true,
  9322. configurable: true
  9323. });
  9324. Object.defineProperty(Engine, "INCR", {
  9325. get: function () {
  9326. return Engine._INCR;
  9327. },
  9328. enumerable: true,
  9329. configurable: true
  9330. });
  9331. Object.defineProperty(Engine, "DECR", {
  9332. get: function () {
  9333. return Engine._DECR;
  9334. },
  9335. enumerable: true,
  9336. configurable: true
  9337. });
  9338. Object.defineProperty(Engine, "INVERT", {
  9339. get: function () {
  9340. return Engine._INVERT;
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. Object.defineProperty(Engine, "INCR_WRAP", {
  9346. get: function () {
  9347. return Engine._INCR_WRAP;
  9348. },
  9349. enumerable: true,
  9350. configurable: true
  9351. });
  9352. Object.defineProperty(Engine, "DECR_WRAP", {
  9353. get: function () {
  9354. return Engine._DECR_WRAP;
  9355. },
  9356. enumerable: true,
  9357. configurable: true
  9358. });
  9359. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9360. get: function () {
  9361. return Engine._ALPHA_DISABLE;
  9362. },
  9363. enumerable: true,
  9364. configurable: true
  9365. });
  9366. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9367. get: function () {
  9368. return Engine._ALPHA_ONEONE;
  9369. },
  9370. enumerable: true,
  9371. configurable: true
  9372. });
  9373. Object.defineProperty(Engine, "ALPHA_ADD", {
  9374. get: function () {
  9375. return Engine._ALPHA_ADD;
  9376. },
  9377. enumerable: true,
  9378. configurable: true
  9379. });
  9380. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9381. get: function () {
  9382. return Engine._ALPHA_COMBINE;
  9383. },
  9384. enumerable: true,
  9385. configurable: true
  9386. });
  9387. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9388. get: function () {
  9389. return Engine._ALPHA_SUBTRACT;
  9390. },
  9391. enumerable: true,
  9392. configurable: true
  9393. });
  9394. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9395. get: function () {
  9396. return Engine._ALPHA_MULTIPLY;
  9397. },
  9398. enumerable: true,
  9399. configurable: true
  9400. });
  9401. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9402. get: function () {
  9403. return Engine._ALPHA_MAXIMIZED;
  9404. },
  9405. enumerable: true,
  9406. configurable: true
  9407. });
  9408. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9409. get: function () {
  9410. return Engine._ALPHA_PREMULTIPLIED;
  9411. },
  9412. enumerable: true,
  9413. configurable: true
  9414. });
  9415. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9416. get: function () {
  9417. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9418. },
  9419. enumerable: true,
  9420. configurable: true
  9421. });
  9422. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9423. get: function () {
  9424. return Engine._ALPHA_INTERPOLATE;
  9425. },
  9426. enumerable: true,
  9427. configurable: true
  9428. });
  9429. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9430. get: function () {
  9431. return Engine._ALPHA_SCREENMODE;
  9432. },
  9433. enumerable: true,
  9434. configurable: true
  9435. });
  9436. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9437. get: function () {
  9438. return Engine._DELAYLOADSTATE_NONE;
  9439. },
  9440. enumerable: true,
  9441. configurable: true
  9442. });
  9443. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9444. get: function () {
  9445. return Engine._DELAYLOADSTATE_LOADED;
  9446. },
  9447. enumerable: true,
  9448. configurable: true
  9449. });
  9450. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9451. get: function () {
  9452. return Engine._DELAYLOADSTATE_LOADING;
  9453. },
  9454. enumerable: true,
  9455. configurable: true
  9456. });
  9457. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9458. get: function () {
  9459. return Engine._DELAYLOADSTATE_NOTLOADED;
  9460. },
  9461. enumerable: true,
  9462. configurable: true
  9463. });
  9464. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9465. get: function () {
  9466. return Engine._TEXTUREFORMAT_ALPHA;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9472. get: function () {
  9473. return Engine._TEXTUREFORMAT_LUMINANCE;
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9479. get: function () {
  9480. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9486. get: function () {
  9487. return Engine._TEXTUREFORMAT_RGB;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9493. get: function () {
  9494. return Engine._TEXTUREFORMAT_RGBA;
  9495. },
  9496. enumerable: true,
  9497. configurable: true
  9498. });
  9499. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9500. get: function () {
  9501. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9502. },
  9503. enumerable: true,
  9504. configurable: true
  9505. });
  9506. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9507. get: function () {
  9508. return Engine._TEXTURETYPE_FLOAT;
  9509. },
  9510. enumerable: true,
  9511. configurable: true
  9512. });
  9513. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9514. get: function () {
  9515. return Engine._TEXTURETYPE_HALF_FLOAT;
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9521. get: function () {
  9522. return Engine._SCALEMODE_FLOOR;
  9523. },
  9524. enumerable: true,
  9525. configurable: true
  9526. });
  9527. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9528. get: function () {
  9529. return Engine._SCALEMODE_NEAREST;
  9530. },
  9531. enumerable: true,
  9532. configurable: true
  9533. });
  9534. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9535. get: function () {
  9536. return Engine._SCALEMODE_CEILING;
  9537. },
  9538. enumerable: true,
  9539. configurable: true
  9540. });
  9541. Object.defineProperty(Engine, "Version", {
  9542. get: function () {
  9543. return "3.2.0-alpha4";
  9544. },
  9545. enumerable: true,
  9546. configurable: true
  9547. });
  9548. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9549. get: function () {
  9550. return this._vrExclusivePointerMode;
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9556. get: function () {
  9557. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9558. },
  9559. enumerable: true,
  9560. configurable: true
  9561. });
  9562. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9563. get: function () {
  9564. return this._webGLVersion < 2 || this.forcePOTTextures;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(Engine.prototype, "badOS", {
  9570. get: function () {
  9571. return this._badOS;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9577. get: function () {
  9578. return this._badDesktopOS;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9584. get: function () {
  9585. return this._performanceMonitor;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9591. get: function () {
  9592. return this._texturesSupported;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9598. get: function () {
  9599. return this._textureFormatInUse;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(Engine.prototype, "currentViewport", {
  9605. get: function () {
  9606. return this._cachedViewport;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9612. // Empty texture
  9613. get: function () {
  9614. if (!this._emptyTexture) {
  9615. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9616. }
  9617. return this._emptyTexture;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9623. get: function () {
  9624. if (!this._emptyTexture3D) {
  9625. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9626. }
  9627. return this._emptyTexture3D;
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9633. get: function () {
  9634. if (!this._emptyCubeTexture) {
  9635. var faceData = new Uint8Array(4);
  9636. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9637. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9638. }
  9639. return this._emptyCubeTexture;
  9640. },
  9641. enumerable: true,
  9642. configurable: true
  9643. });
  9644. Engine.prototype._rebuildInternalTextures = function () {
  9645. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9646. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9647. var internalTexture = currentState_1[_i];
  9648. internalTexture._rebuild();
  9649. }
  9650. };
  9651. Engine.prototype._rebuildEffects = function () {
  9652. for (var key in this._compiledEffects) {
  9653. var effect = this._compiledEffects[key];
  9654. effect._prepareEffect();
  9655. }
  9656. BABYLON.Effect.ResetCache();
  9657. };
  9658. Engine.prototype._rebuildBuffers = function () {
  9659. // Index / Vertex
  9660. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9661. var scene = _a[_i];
  9662. scene.resetCachedMaterial();
  9663. scene._rebuildGeometries();
  9664. scene._rebuildTextures();
  9665. }
  9666. // Uniforms
  9667. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9668. var uniformBuffer = _c[_b];
  9669. uniformBuffer._rebuild();
  9670. }
  9671. };
  9672. Engine.prototype._initGLContext = function () {
  9673. // Caps
  9674. this._caps = new EngineCapabilities();
  9675. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9676. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9677. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9678. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9679. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9680. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9681. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9682. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9683. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9684. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9685. // Infos
  9686. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9687. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9688. if (rendererInfo != null) {
  9689. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9690. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9691. }
  9692. if (!this._glVendor) {
  9693. this._glVendor = "Unknown vendor";
  9694. }
  9695. if (!this._glRenderer) {
  9696. this._glRenderer = "Unknown renderer";
  9697. }
  9698. // Constants
  9699. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9700. if (this._gl.RGBA16F !== 0x881A) {
  9701. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9702. }
  9703. if (this._gl.RGBA32F !== 0x8814) {
  9704. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9705. }
  9706. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9707. this._gl.DEPTH24_STENCIL8 = 35056;
  9708. }
  9709. // Extensions
  9710. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9711. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9712. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9713. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9714. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9715. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9716. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9717. 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');
  9718. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9719. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9720. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9721. this._caps.highPrecisionShaderSupported = true;
  9722. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9723. if (this._caps.timerQuery) {
  9724. if (this._webGLVersion === 1) {
  9725. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9726. }
  9727. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9728. }
  9729. // Checks if some of the format renders first to allow the use of webgl inspector.
  9730. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9731. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9732. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9733. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9734. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9735. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9736. if (this._webGLVersion > 1) {
  9737. this._gl.HALF_FLOAT_OES = 0x140B;
  9738. }
  9739. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9740. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9741. // Draw buffers
  9742. if (this._webGLVersion > 1) {
  9743. this._caps.drawBuffersExtension = true;
  9744. }
  9745. else {
  9746. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9747. if (drawBuffersExtension !== null) {
  9748. this._caps.drawBuffersExtension = true;
  9749. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9750. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9751. for (var i = 0; i < 16; i++) {
  9752. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9753. }
  9754. }
  9755. else {
  9756. this._caps.drawBuffersExtension = false;
  9757. }
  9758. }
  9759. // Depth Texture
  9760. if (this._webGLVersion > 1) {
  9761. this._caps.depthTextureExtension = true;
  9762. }
  9763. else {
  9764. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9765. if (depthTextureExtension != null) {
  9766. this._caps.depthTextureExtension = true;
  9767. }
  9768. }
  9769. // Vertex array object
  9770. if (this._webGLVersion > 1) {
  9771. this._caps.vertexArrayObject = true;
  9772. }
  9773. else {
  9774. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9775. if (vertexArrayObjectExtension != null) {
  9776. this._caps.vertexArrayObject = true;
  9777. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9778. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9779. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9780. }
  9781. else {
  9782. this._caps.vertexArrayObject = false;
  9783. }
  9784. }
  9785. // Instances count
  9786. if (this._webGLVersion > 1) {
  9787. this._caps.instancedArrays = true;
  9788. }
  9789. else {
  9790. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9791. if (instanceExtension != null) {
  9792. this._caps.instancedArrays = true;
  9793. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9794. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9795. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9796. }
  9797. else {
  9798. this._caps.instancedArrays = false;
  9799. }
  9800. }
  9801. // Intelligently add supported compressed formats in order to check for.
  9802. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9803. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9804. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9805. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9806. if (this._caps.astc)
  9807. this.texturesSupported.push('-astc.ktx');
  9808. if (this._caps.s3tc)
  9809. this.texturesSupported.push('-dxt.ktx');
  9810. if (this._caps.pvrtc)
  9811. this.texturesSupported.push('-pvrtc.ktx');
  9812. if (this._caps.etc2)
  9813. this.texturesSupported.push('-etc2.ktx');
  9814. if (this._caps.etc1)
  9815. this.texturesSupported.push('-etc1.ktx');
  9816. if (this._gl.getShaderPrecisionFormat) {
  9817. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9818. if (highp) {
  9819. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9820. }
  9821. }
  9822. // Depth buffer
  9823. this.setDepthBuffer(true);
  9824. this.setDepthFunctionToLessOrEqual();
  9825. this.setDepthWrite(true);
  9826. // Texture maps
  9827. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9828. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9829. this._nextFreeTextureSlots.push(slot);
  9830. }
  9831. };
  9832. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9833. get: function () {
  9834. return this._webGLVersion;
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9840. /**
  9841. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9842. */
  9843. get: function () {
  9844. return this._isStencilEnable;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Engine.prototype._prepareWorkingCanvas = function () {
  9850. if (this._workingCanvas) {
  9851. return;
  9852. }
  9853. this._workingCanvas = document.createElement("canvas");
  9854. var context = this._workingCanvas.getContext("2d");
  9855. if (context) {
  9856. this._workingContext = context;
  9857. }
  9858. };
  9859. Engine.prototype.resetTextureCache = function () {
  9860. for (var key in this._boundTexturesCache) {
  9861. var boundTexture = this._boundTexturesCache[key];
  9862. if (boundTexture) {
  9863. this._removeDesignatedSlot(boundTexture);
  9864. }
  9865. this._boundTexturesCache[key] = null;
  9866. }
  9867. this._nextFreeTextureSlots = [];
  9868. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9869. this._nextFreeTextureSlots.push(slot);
  9870. }
  9871. this._activeChannel = -1;
  9872. };
  9873. Engine.prototype.isDeterministicLockStep = function () {
  9874. return this._deterministicLockstep;
  9875. };
  9876. Engine.prototype.getLockstepMaxSteps = function () {
  9877. return this._lockstepMaxSteps;
  9878. };
  9879. Engine.prototype.getGlInfo = function () {
  9880. return {
  9881. vendor: this._glVendor,
  9882. renderer: this._glRenderer,
  9883. version: this._glVersion
  9884. };
  9885. };
  9886. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9887. if (useScreen === void 0) { useScreen = false; }
  9888. var viewport = camera.viewport;
  9889. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9890. };
  9891. Engine.prototype.getRenderWidth = function (useScreen) {
  9892. if (useScreen === void 0) { useScreen = false; }
  9893. if (!useScreen && this._currentRenderTarget) {
  9894. return this._currentRenderTarget.width;
  9895. }
  9896. return this._gl.drawingBufferWidth;
  9897. };
  9898. Engine.prototype.getRenderHeight = function (useScreen) {
  9899. if (useScreen === void 0) { useScreen = false; }
  9900. if (!useScreen && this._currentRenderTarget) {
  9901. return this._currentRenderTarget.height;
  9902. }
  9903. return this._gl.drawingBufferHeight;
  9904. };
  9905. Engine.prototype.getRenderingCanvas = function () {
  9906. return this._renderingCanvas;
  9907. };
  9908. Engine.prototype.getRenderingCanvasClientRect = function () {
  9909. if (!this._renderingCanvas) {
  9910. return null;
  9911. }
  9912. return this._renderingCanvas.getBoundingClientRect();
  9913. };
  9914. Engine.prototype.setHardwareScalingLevel = function (level) {
  9915. this._hardwareScalingLevel = level;
  9916. this.resize();
  9917. };
  9918. Engine.prototype.getHardwareScalingLevel = function () {
  9919. return this._hardwareScalingLevel;
  9920. };
  9921. Engine.prototype.getLoadedTexturesCache = function () {
  9922. return this._internalTexturesCache;
  9923. };
  9924. Engine.prototype.getCaps = function () {
  9925. return this._caps;
  9926. };
  9927. Object.defineProperty(Engine.prototype, "drawCalls", {
  9928. /** The number of draw calls submitted last frame */
  9929. get: function () {
  9930. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9931. return 0;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9937. get: function () {
  9938. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9939. return null;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Engine.prototype.getDepthFunction = function () {
  9945. return this._depthCullingState.depthFunc;
  9946. };
  9947. Engine.prototype.setDepthFunction = function (depthFunc) {
  9948. this._depthCullingState.depthFunc = depthFunc;
  9949. };
  9950. Engine.prototype.setDepthFunctionToGreater = function () {
  9951. this._depthCullingState.depthFunc = this._gl.GREATER;
  9952. };
  9953. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9954. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9955. };
  9956. Engine.prototype.setDepthFunctionToLess = function () {
  9957. this._depthCullingState.depthFunc = this._gl.LESS;
  9958. };
  9959. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9960. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9961. };
  9962. Engine.prototype.getStencilBuffer = function () {
  9963. return this._stencilState.stencilTest;
  9964. };
  9965. Engine.prototype.setStencilBuffer = function (enable) {
  9966. this._stencilState.stencilTest = enable;
  9967. };
  9968. Engine.prototype.getStencilMask = function () {
  9969. return this._stencilState.stencilMask;
  9970. };
  9971. Engine.prototype.setStencilMask = function (mask) {
  9972. this._stencilState.stencilMask = mask;
  9973. };
  9974. Engine.prototype.getStencilFunction = function () {
  9975. return this._stencilState.stencilFunc;
  9976. };
  9977. Engine.prototype.getStencilFunctionReference = function () {
  9978. return this._stencilState.stencilFuncRef;
  9979. };
  9980. Engine.prototype.getStencilFunctionMask = function () {
  9981. return this._stencilState.stencilFuncMask;
  9982. };
  9983. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9984. this._stencilState.stencilFunc = stencilFunc;
  9985. };
  9986. Engine.prototype.setStencilFunctionReference = function (reference) {
  9987. this._stencilState.stencilFuncRef = reference;
  9988. };
  9989. Engine.prototype.setStencilFunctionMask = function (mask) {
  9990. this._stencilState.stencilFuncMask = mask;
  9991. };
  9992. Engine.prototype.getStencilOperationFail = function () {
  9993. return this._stencilState.stencilOpStencilFail;
  9994. };
  9995. Engine.prototype.getStencilOperationDepthFail = function () {
  9996. return this._stencilState.stencilOpDepthFail;
  9997. };
  9998. Engine.prototype.getStencilOperationPass = function () {
  9999. return this._stencilState.stencilOpStencilDepthPass;
  10000. };
  10001. Engine.prototype.setStencilOperationFail = function (operation) {
  10002. this._stencilState.stencilOpStencilFail = operation;
  10003. };
  10004. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10005. this._stencilState.stencilOpDepthFail = operation;
  10006. };
  10007. Engine.prototype.setStencilOperationPass = function (operation) {
  10008. this._stencilState.stencilOpStencilDepthPass = operation;
  10009. };
  10010. Engine.prototype.setDitheringState = function (value) {
  10011. if (value) {
  10012. this._gl.enable(this._gl.DITHER);
  10013. }
  10014. else {
  10015. this._gl.disable(this._gl.DITHER);
  10016. }
  10017. };
  10018. Engine.prototype.setRasterizerState = function (value) {
  10019. if (value) {
  10020. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10021. }
  10022. else {
  10023. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10024. }
  10025. };
  10026. /**
  10027. * stop executing a render loop function and remove it from the execution array
  10028. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10029. */
  10030. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10031. if (!renderFunction) {
  10032. this._activeRenderLoops = [];
  10033. return;
  10034. }
  10035. var index = this._activeRenderLoops.indexOf(renderFunction);
  10036. if (index >= 0) {
  10037. this._activeRenderLoops.splice(index, 1);
  10038. }
  10039. };
  10040. Engine.prototype._renderLoop = function () {
  10041. if (!this._contextWasLost) {
  10042. var shouldRender = true;
  10043. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10044. shouldRender = false;
  10045. }
  10046. if (shouldRender) {
  10047. // Start new frame
  10048. this.beginFrame();
  10049. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10050. var renderFunction = this._activeRenderLoops[index];
  10051. renderFunction();
  10052. }
  10053. // Present
  10054. this.endFrame();
  10055. }
  10056. }
  10057. if (this._activeRenderLoops.length > 0) {
  10058. // Register new frame
  10059. var requester = null;
  10060. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10061. requester = this._vrDisplay;
  10062. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10063. }
  10064. else {
  10065. this._renderingQueueLaunched = false;
  10066. }
  10067. };
  10068. /**
  10069. * Register and execute a render loop. The engine can have more than one render function.
  10070. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10071. * @example
  10072. * engine.runRenderLoop(function () {
  10073. * scene.render()
  10074. * })
  10075. */
  10076. Engine.prototype.runRenderLoop = function (renderFunction) {
  10077. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10078. return;
  10079. }
  10080. this._activeRenderLoops.push(renderFunction);
  10081. if (!this._renderingQueueLaunched) {
  10082. this._renderingQueueLaunched = true;
  10083. this._bindedRenderFunction = this._renderLoop.bind(this);
  10084. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10085. }
  10086. };
  10087. /**
  10088. * Toggle full screen mode.
  10089. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10090. * @param {any} options - an options object to be sent to the requestFullscreen function
  10091. */
  10092. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10093. if (this.isFullscreen) {
  10094. BABYLON.Tools.ExitFullscreen();
  10095. }
  10096. else {
  10097. this._pointerLockRequested = requestPointerLock;
  10098. if (this._renderingCanvas) {
  10099. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10100. }
  10101. }
  10102. };
  10103. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10104. if (stencil === void 0) { stencil = false; }
  10105. this.applyStates();
  10106. var mode = 0;
  10107. if (backBuffer && color) {
  10108. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10109. mode |= this._gl.COLOR_BUFFER_BIT;
  10110. }
  10111. if (depth) {
  10112. this._gl.clearDepth(1.0);
  10113. mode |= this._gl.DEPTH_BUFFER_BIT;
  10114. }
  10115. if (stencil) {
  10116. this._gl.clearStencil(0);
  10117. mode |= this._gl.STENCIL_BUFFER_BIT;
  10118. }
  10119. this._gl.clear(mode);
  10120. };
  10121. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10122. var gl = this._gl;
  10123. // Save state
  10124. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10125. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10126. // Change state
  10127. gl.enable(gl.SCISSOR_TEST);
  10128. gl.scissor(x, y, width, height);
  10129. // Clear
  10130. this.clear(clearColor, true, true, true);
  10131. // Restore state
  10132. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10133. if (curScissor === true) {
  10134. gl.enable(gl.SCISSOR_TEST);
  10135. }
  10136. else {
  10137. gl.disable(gl.SCISSOR_TEST);
  10138. }
  10139. };
  10140. /**
  10141. * Set the WebGL's viewport
  10142. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10143. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10144. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10145. */
  10146. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10147. var width = requiredWidth || this.getRenderWidth();
  10148. var height = requiredHeight || this.getRenderHeight();
  10149. var x = viewport.x || 0;
  10150. var y = viewport.y || 0;
  10151. this._cachedViewport = viewport;
  10152. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10153. };
  10154. /**
  10155. * Directly set the WebGL Viewport
  10156. * The x, y, width & height are directly passed to the WebGL call
  10157. * @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.
  10158. */
  10159. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10160. var currentViewport = this._cachedViewport;
  10161. this._cachedViewport = null;
  10162. this._gl.viewport(x, y, width, height);
  10163. return currentViewport;
  10164. };
  10165. Engine.prototype.beginFrame = function () {
  10166. this.onBeginFrameObservable.notifyObservers(this);
  10167. this._measureFps();
  10168. };
  10169. Engine.prototype.endFrame = function () {
  10170. //force a flush in case we are using a bad OS.
  10171. if (this._badOS) {
  10172. this.flushFramebuffer();
  10173. }
  10174. //submit frame to the vr device, if enabled
  10175. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10176. // TODO: We should only submit the frame if we read frameData successfully.
  10177. this._vrDisplay.submitFrame();
  10178. }
  10179. this.onEndFrameObservable.notifyObservers(this);
  10180. };
  10181. /**
  10182. * resize the view according to the canvas' size.
  10183. * @example
  10184. * window.addEventListener("resize", function () {
  10185. * engine.resize();
  10186. * });
  10187. */
  10188. Engine.prototype.resize = function () {
  10189. // We're not resizing the size of the canvas while in VR mode & presenting
  10190. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10191. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10192. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10193. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10194. }
  10195. };
  10196. /**
  10197. * force a specific size of the canvas
  10198. * @param {number} width - the new canvas' width
  10199. * @param {number} height - the new canvas' height
  10200. */
  10201. Engine.prototype.setSize = function (width, height) {
  10202. if (!this._renderingCanvas) {
  10203. return;
  10204. }
  10205. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10206. return;
  10207. }
  10208. this._renderingCanvas.width = width;
  10209. this._renderingCanvas.height = height;
  10210. for (var index = 0; index < this.scenes.length; index++) {
  10211. var scene = this.scenes[index];
  10212. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10213. var cam = scene.cameras[camIndex];
  10214. cam._currentRenderId = 0;
  10215. }
  10216. }
  10217. if (this.onResizeObservable.hasObservers) {
  10218. this.onResizeObservable.notifyObservers(this);
  10219. }
  10220. };
  10221. // WebVR functions
  10222. Engine.prototype.isVRDevicePresent = function () {
  10223. return !!this._vrDisplay;
  10224. };
  10225. Engine.prototype.getVRDevice = function () {
  10226. return this._vrDisplay;
  10227. };
  10228. Engine.prototype.initWebVR = function () {
  10229. var _this = this;
  10230. var notifyObservers = function () {
  10231. var eventArgs = {
  10232. vrDisplay: _this._vrDisplay,
  10233. vrSupported: _this._vrSupported
  10234. };
  10235. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10236. };
  10237. if (!this._onVrDisplayConnect) {
  10238. this._onVrDisplayConnect = function (event) {
  10239. _this._vrDisplay = event.display;
  10240. notifyObservers();
  10241. };
  10242. this._onVrDisplayDisconnect = function () {
  10243. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10244. _this._vrDisplay = undefined;
  10245. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10246. notifyObservers();
  10247. };
  10248. this._onVrDisplayPresentChange = function () {
  10249. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10250. };
  10251. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10252. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10253. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10254. }
  10255. this._getVRDisplays(notifyObservers);
  10256. return this.onVRDisplayChangedObservable;
  10257. };
  10258. Engine.prototype.enableVR = function () {
  10259. var _this = this;
  10260. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10261. var onResolved = function () {
  10262. _this.onVRRequestPresentComplete.notifyObservers(true);
  10263. _this._onVRFullScreenTriggered();
  10264. };
  10265. var onRejected = function () {
  10266. _this.onVRRequestPresentComplete.notifyObservers(false);
  10267. };
  10268. this.onVRRequestPresentStart.notifyObservers(this);
  10269. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10270. }
  10271. };
  10272. Engine.prototype.disableVR = function () {
  10273. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10274. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10275. }
  10276. };
  10277. Engine.prototype._getVRDisplays = function (callback) {
  10278. var _this = this;
  10279. var getWebVRDevices = function (devices) {
  10280. _this._vrSupported = true;
  10281. // note that devices may actually be an empty array. This is fine;
  10282. // we expect this._vrDisplay to be undefined in this case.
  10283. return _this._vrDisplay = devices[0];
  10284. };
  10285. if (navigator.getVRDisplays) {
  10286. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10287. // TODO: System CANNOT support WebVR, despite API presence.
  10288. _this._vrSupported = false;
  10289. callback();
  10290. });
  10291. }
  10292. else {
  10293. // TODO: Browser does not support WebVR
  10294. this._vrDisplay = undefined;
  10295. this._vrSupported = false;
  10296. callback();
  10297. }
  10298. };
  10299. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10300. if (this._currentRenderTarget) {
  10301. this.unBindFramebuffer(this._currentRenderTarget);
  10302. }
  10303. this._currentRenderTarget = texture;
  10304. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10305. var gl = this._gl;
  10306. if (texture.isCube) {
  10307. if (faceIndex === undefined) {
  10308. faceIndex = 0;
  10309. }
  10310. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10311. }
  10312. if (this._cachedViewport && !forceFullscreenViewport) {
  10313. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10314. }
  10315. else {
  10316. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10317. }
  10318. this.wipeCaches();
  10319. };
  10320. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10321. if (this._currentFramebuffer !== framebuffer) {
  10322. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10323. this._currentFramebuffer = framebuffer;
  10324. }
  10325. };
  10326. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10327. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10328. this._currentRenderTarget = null;
  10329. // If MSAA, we need to bitblt back to main texture
  10330. var gl = this._gl;
  10331. if (texture._MSAAFramebuffer) {
  10332. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10333. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10334. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10335. }
  10336. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10337. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10338. gl.generateMipmap(gl.TEXTURE_2D);
  10339. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10340. }
  10341. if (onBeforeUnbind) {
  10342. if (texture._MSAAFramebuffer) {
  10343. // Bind the correct framebuffer
  10344. this.bindUnboundFramebuffer(texture._framebuffer);
  10345. }
  10346. onBeforeUnbind();
  10347. }
  10348. this.bindUnboundFramebuffer(null);
  10349. };
  10350. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10351. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10352. this._currentRenderTarget = null;
  10353. // If MSAA, we need to bitblt back to main texture
  10354. var gl = this._gl;
  10355. if (textures[0]._MSAAFramebuffer) {
  10356. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10357. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10358. var attachments = textures[0]._attachments;
  10359. if (!attachments) {
  10360. attachments = new Array(textures.length);
  10361. textures[0]._attachments = attachments;
  10362. }
  10363. for (var i = 0; i < textures.length; i++) {
  10364. var texture = textures[i];
  10365. for (var j = 0; j < attachments.length; j++) {
  10366. attachments[j] = gl.NONE;
  10367. }
  10368. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10369. gl.readBuffer(attachments[i]);
  10370. gl.drawBuffers(attachments);
  10371. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10372. }
  10373. for (var i = 0; i < attachments.length; i++) {
  10374. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10375. }
  10376. gl.drawBuffers(attachments);
  10377. }
  10378. for (var i = 0; i < textures.length; i++) {
  10379. var texture = textures[i];
  10380. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10381. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10382. gl.generateMipmap(gl.TEXTURE_2D);
  10383. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10384. }
  10385. }
  10386. if (onBeforeUnbind) {
  10387. if (textures[0]._MSAAFramebuffer) {
  10388. // Bind the correct framebuffer
  10389. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10390. }
  10391. onBeforeUnbind();
  10392. }
  10393. this.bindUnboundFramebuffer(null);
  10394. };
  10395. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10396. if (texture.generateMipMaps) {
  10397. var gl = this._gl;
  10398. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10399. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10401. }
  10402. };
  10403. Engine.prototype.flushFramebuffer = function () {
  10404. this._gl.flush();
  10405. };
  10406. Engine.prototype.restoreDefaultFramebuffer = function () {
  10407. if (this._currentRenderTarget) {
  10408. this.unBindFramebuffer(this._currentRenderTarget);
  10409. }
  10410. else {
  10411. this.bindUnboundFramebuffer(null);
  10412. }
  10413. if (this._cachedViewport) {
  10414. this.setViewport(this._cachedViewport);
  10415. }
  10416. this.wipeCaches();
  10417. };
  10418. // UBOs
  10419. Engine.prototype.createUniformBuffer = function (elements) {
  10420. var ubo = this._gl.createBuffer();
  10421. if (!ubo) {
  10422. throw new Error("Unable to create uniform buffer");
  10423. }
  10424. this.bindUniformBuffer(ubo);
  10425. if (elements instanceof Float32Array) {
  10426. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10427. }
  10428. else {
  10429. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10430. }
  10431. this.bindUniformBuffer(null);
  10432. ubo.references = 1;
  10433. return ubo;
  10434. };
  10435. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10436. var ubo = this._gl.createBuffer();
  10437. if (!ubo) {
  10438. throw new Error("Unable to create dynamic uniform buffer");
  10439. }
  10440. this.bindUniformBuffer(ubo);
  10441. if (elements instanceof Float32Array) {
  10442. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10443. }
  10444. else {
  10445. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10446. }
  10447. this.bindUniformBuffer(null);
  10448. ubo.references = 1;
  10449. return ubo;
  10450. };
  10451. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10452. this.bindUniformBuffer(uniformBuffer);
  10453. if (offset === undefined) {
  10454. offset = 0;
  10455. }
  10456. if (count === undefined) {
  10457. if (elements instanceof Float32Array) {
  10458. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10459. }
  10460. else {
  10461. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10462. }
  10463. }
  10464. else {
  10465. if (elements instanceof Float32Array) {
  10466. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10467. }
  10468. else {
  10469. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10470. }
  10471. }
  10472. this.bindUniformBuffer(null);
  10473. };
  10474. // VBOs
  10475. Engine.prototype._resetVertexBufferBinding = function () {
  10476. this.bindArrayBuffer(null);
  10477. this._cachedVertexBuffers = null;
  10478. };
  10479. Engine.prototype.createVertexBuffer = function (vertices) {
  10480. var vbo = this._gl.createBuffer();
  10481. if (!vbo) {
  10482. throw new Error("Unable to create vertex buffer");
  10483. }
  10484. this.bindArrayBuffer(vbo);
  10485. if (vertices instanceof Float32Array) {
  10486. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10487. }
  10488. else {
  10489. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10490. }
  10491. this._resetVertexBufferBinding();
  10492. vbo.references = 1;
  10493. return vbo;
  10494. };
  10495. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10496. var vbo = this._gl.createBuffer();
  10497. if (!vbo) {
  10498. throw new Error("Unable to create dynamic vertex buffer");
  10499. }
  10500. this.bindArrayBuffer(vbo);
  10501. if (vertices instanceof Float32Array) {
  10502. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10503. }
  10504. else {
  10505. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10506. }
  10507. this._resetVertexBufferBinding();
  10508. vbo.references = 1;
  10509. return vbo;
  10510. };
  10511. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10512. if (offset === void 0) { offset = 0; }
  10513. // Force cache update
  10514. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10515. this.bindIndexBuffer(indexBuffer);
  10516. var arrayBuffer;
  10517. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10518. arrayBuffer = indices;
  10519. }
  10520. else {
  10521. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10522. }
  10523. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10524. this._resetIndexBufferBinding();
  10525. };
  10526. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10527. this.bindArrayBuffer(vertexBuffer);
  10528. if (offset === undefined) {
  10529. offset = 0;
  10530. }
  10531. if (count === undefined) {
  10532. if (vertices instanceof Float32Array) {
  10533. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10534. }
  10535. else {
  10536. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10537. }
  10538. }
  10539. else {
  10540. if (vertices instanceof Float32Array) {
  10541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10542. }
  10543. else {
  10544. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10545. }
  10546. }
  10547. this._resetVertexBufferBinding();
  10548. };
  10549. Engine.prototype._resetIndexBufferBinding = function () {
  10550. this.bindIndexBuffer(null);
  10551. this._cachedIndexBuffer = null;
  10552. };
  10553. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10554. var vbo = this._gl.createBuffer();
  10555. if (!vbo) {
  10556. throw new Error("Unable to create index buffer");
  10557. }
  10558. this.bindIndexBuffer(vbo);
  10559. // Check for 32 bits indices
  10560. var arrayBuffer;
  10561. var need32Bits = false;
  10562. if (indices instanceof Uint16Array) {
  10563. arrayBuffer = indices;
  10564. }
  10565. else {
  10566. //check 32 bit support
  10567. if (this._caps.uintIndices) {
  10568. if (indices instanceof Uint32Array) {
  10569. arrayBuffer = indices;
  10570. need32Bits = true;
  10571. }
  10572. else {
  10573. //number[] or Int32Array, check if 32 bit is necessary
  10574. for (var index = 0; index < indices.length; index++) {
  10575. if (indices[index] > 65535) {
  10576. need32Bits = true;
  10577. break;
  10578. }
  10579. }
  10580. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10581. }
  10582. }
  10583. else {
  10584. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10585. arrayBuffer = new Uint16Array(indices);
  10586. }
  10587. }
  10588. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10589. this._resetIndexBufferBinding();
  10590. vbo.references = 1;
  10591. vbo.is32Bits = need32Bits;
  10592. return vbo;
  10593. };
  10594. Engine.prototype.bindArrayBuffer = function (buffer) {
  10595. if (!this._vaoRecordInProgress) {
  10596. this._unbindVertexArrayObject();
  10597. }
  10598. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10599. };
  10600. Engine.prototype.bindUniformBuffer = function (buffer) {
  10601. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10602. };
  10603. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10604. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10605. };
  10606. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10607. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10608. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10609. };
  10610. ;
  10611. Engine.prototype.bindIndexBuffer = function (buffer) {
  10612. if (!this._vaoRecordInProgress) {
  10613. this._unbindVertexArrayObject();
  10614. }
  10615. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10616. };
  10617. Engine.prototype.bindBuffer = function (buffer, target) {
  10618. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10619. this._gl.bindBuffer(target, buffer);
  10620. this._currentBoundBuffer[target] = buffer;
  10621. }
  10622. };
  10623. Engine.prototype.updateArrayBuffer = function (data) {
  10624. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10625. };
  10626. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10627. var pointer = this._currentBufferPointers[indx];
  10628. var changed = false;
  10629. if (!pointer.active) {
  10630. changed = true;
  10631. pointer.active = true;
  10632. pointer.index = indx;
  10633. pointer.size = size;
  10634. pointer.type = type;
  10635. pointer.normalized = normalized;
  10636. pointer.stride = stride;
  10637. pointer.offset = offset;
  10638. pointer.buffer = buffer;
  10639. }
  10640. else {
  10641. if (pointer.buffer !== buffer) {
  10642. pointer.buffer = buffer;
  10643. changed = true;
  10644. }
  10645. if (pointer.size !== size) {
  10646. pointer.size = size;
  10647. changed = true;
  10648. }
  10649. if (pointer.type !== type) {
  10650. pointer.type = type;
  10651. changed = true;
  10652. }
  10653. if (pointer.normalized !== normalized) {
  10654. pointer.normalized = normalized;
  10655. changed = true;
  10656. }
  10657. if (pointer.stride !== stride) {
  10658. pointer.stride = stride;
  10659. changed = true;
  10660. }
  10661. if (pointer.offset !== offset) {
  10662. pointer.offset = offset;
  10663. changed = true;
  10664. }
  10665. }
  10666. if (changed || this._vaoRecordInProgress) {
  10667. this.bindArrayBuffer(buffer);
  10668. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10669. }
  10670. };
  10671. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10672. if (indexBuffer == null) {
  10673. return;
  10674. }
  10675. if (this._cachedIndexBuffer !== indexBuffer) {
  10676. this._cachedIndexBuffer = indexBuffer;
  10677. this.bindIndexBuffer(indexBuffer);
  10678. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10679. }
  10680. };
  10681. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10682. var attributes = effect.getAttributesNames();
  10683. if (!this._vaoRecordInProgress) {
  10684. this._unbindVertexArrayObject();
  10685. }
  10686. this.unbindAllAttributes();
  10687. for (var index = 0; index < attributes.length; index++) {
  10688. var order = effect.getAttributeLocation(index);
  10689. if (order >= 0) {
  10690. var vertexBuffer = vertexBuffers[attributes[index]];
  10691. if (!vertexBuffer) {
  10692. continue;
  10693. }
  10694. this._gl.enableVertexAttribArray(order);
  10695. if (!this._vaoRecordInProgress) {
  10696. this._vertexAttribArraysEnabled[order] = true;
  10697. }
  10698. var buffer = vertexBuffer.getBuffer();
  10699. if (buffer) {
  10700. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10701. if (vertexBuffer.getIsInstanced()) {
  10702. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10703. if (!this._vaoRecordInProgress) {
  10704. this._currentInstanceLocations.push(order);
  10705. this._currentInstanceBuffers.push(buffer);
  10706. }
  10707. }
  10708. }
  10709. }
  10710. }
  10711. };
  10712. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10713. var vao = this._gl.createVertexArray();
  10714. this._vaoRecordInProgress = true;
  10715. this._gl.bindVertexArray(vao);
  10716. this._mustWipeVertexAttributes = true;
  10717. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10718. this.bindIndexBuffer(indexBuffer);
  10719. this._vaoRecordInProgress = false;
  10720. this._gl.bindVertexArray(null);
  10721. return vao;
  10722. };
  10723. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10724. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10725. this._cachedVertexArrayObject = vertexArrayObject;
  10726. this._gl.bindVertexArray(vertexArrayObject);
  10727. this._cachedVertexBuffers = null;
  10728. this._cachedIndexBuffer = null;
  10729. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10730. this._mustWipeVertexAttributes = true;
  10731. }
  10732. };
  10733. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10734. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10735. this._cachedVertexBuffers = vertexBuffer;
  10736. this._cachedEffectForVertexBuffers = effect;
  10737. var attributesCount = effect.getAttributesCount();
  10738. this._unbindVertexArrayObject();
  10739. this.unbindAllAttributes();
  10740. var offset = 0;
  10741. for (var index = 0; index < attributesCount; index++) {
  10742. if (index < vertexDeclaration.length) {
  10743. var order = effect.getAttributeLocation(index);
  10744. if (order >= 0) {
  10745. this._gl.enableVertexAttribArray(order);
  10746. this._vertexAttribArraysEnabled[order] = true;
  10747. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10748. }
  10749. offset += vertexDeclaration[index] * 4;
  10750. }
  10751. }
  10752. }
  10753. this._bindIndexBufferWithCache(indexBuffer);
  10754. };
  10755. Engine.prototype._unbindVertexArrayObject = function () {
  10756. if (!this._cachedVertexArrayObject) {
  10757. return;
  10758. }
  10759. this._cachedVertexArrayObject = null;
  10760. this._gl.bindVertexArray(null);
  10761. };
  10762. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10763. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10764. this._cachedVertexBuffers = vertexBuffers;
  10765. this._cachedEffectForVertexBuffers = effect;
  10766. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10767. }
  10768. this._bindIndexBufferWithCache(indexBuffer);
  10769. };
  10770. Engine.prototype.unbindInstanceAttributes = function () {
  10771. var boundBuffer;
  10772. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10773. var instancesBuffer = this._currentInstanceBuffers[i];
  10774. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10775. boundBuffer = instancesBuffer;
  10776. this.bindArrayBuffer(instancesBuffer);
  10777. }
  10778. var offsetLocation = this._currentInstanceLocations[i];
  10779. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10780. }
  10781. this._currentInstanceBuffers.length = 0;
  10782. this._currentInstanceLocations.length = 0;
  10783. };
  10784. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10785. this._gl.deleteVertexArray(vao);
  10786. };
  10787. Engine.prototype._releaseBuffer = function (buffer) {
  10788. buffer.references--;
  10789. if (buffer.references === 0) {
  10790. this._gl.deleteBuffer(buffer);
  10791. return true;
  10792. }
  10793. return false;
  10794. };
  10795. Engine.prototype.createInstancesBuffer = function (capacity) {
  10796. var buffer = this._gl.createBuffer();
  10797. if (!buffer) {
  10798. throw new Error("Unable to create instance buffer");
  10799. }
  10800. buffer.capacity = capacity;
  10801. this.bindArrayBuffer(buffer);
  10802. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10803. return buffer;
  10804. };
  10805. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10806. this._gl.deleteBuffer(buffer);
  10807. };
  10808. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10809. this.bindArrayBuffer(instancesBuffer);
  10810. if (data) {
  10811. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10812. }
  10813. if (offsetLocations[0].index !== undefined) {
  10814. var stride = 0;
  10815. for (var i = 0; i < offsetLocations.length; i++) {
  10816. var ai = offsetLocations[i];
  10817. stride += ai.attributeSize * 4;
  10818. }
  10819. for (var i = 0; i < offsetLocations.length; i++) {
  10820. var ai = offsetLocations[i];
  10821. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10822. this._gl.enableVertexAttribArray(ai.index);
  10823. this._vertexAttribArraysEnabled[ai.index] = true;
  10824. }
  10825. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10826. this._gl.vertexAttribDivisor(ai.index, 1);
  10827. this._currentInstanceLocations.push(ai.index);
  10828. this._currentInstanceBuffers.push(instancesBuffer);
  10829. }
  10830. }
  10831. else {
  10832. for (var index = 0; index < 4; index++) {
  10833. var offsetLocation = offsetLocations[index];
  10834. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10835. this._gl.enableVertexAttribArray(offsetLocation);
  10836. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10837. }
  10838. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10839. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10840. this._currentInstanceLocations.push(offsetLocation);
  10841. this._currentInstanceBuffers.push(instancesBuffer);
  10842. }
  10843. }
  10844. };
  10845. Engine.prototype.applyStates = function () {
  10846. this._depthCullingState.apply(this._gl);
  10847. this._stencilState.apply(this._gl);
  10848. this._alphaState.apply(this._gl);
  10849. };
  10850. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10851. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10852. };
  10853. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10854. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10855. };
  10856. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10857. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10858. };
  10859. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10860. // Apply states
  10861. this.applyStates();
  10862. this._drawCalls.addCount(1, false);
  10863. // Render
  10864. var drawMode = this.DrawMode(fillMode);
  10865. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10866. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10867. if (instancesCount) {
  10868. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10869. }
  10870. else {
  10871. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10872. }
  10873. };
  10874. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10875. // Apply states
  10876. this.applyStates();
  10877. this._drawCalls.addCount(1, false);
  10878. var drawMode = this.DrawMode(fillMode);
  10879. if (instancesCount) {
  10880. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10881. }
  10882. else {
  10883. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10884. }
  10885. };
  10886. Engine.prototype.DrawMode = function (fillMode) {
  10887. switch (fillMode) {
  10888. // Triangle views
  10889. case BABYLON.Material.TriangleFillMode:
  10890. return this._gl.TRIANGLES;
  10891. case BABYLON.Material.PointFillMode:
  10892. return this._gl.POINTS;
  10893. case BABYLON.Material.WireFrameFillMode:
  10894. return this._gl.LINES;
  10895. // Draw modes
  10896. case BABYLON.Material.PointListDrawMode:
  10897. return this._gl.POINTS;
  10898. case BABYLON.Material.LineListDrawMode:
  10899. return this._gl.LINES;
  10900. case BABYLON.Material.LineLoopDrawMode:
  10901. return this._gl.LINE_LOOP;
  10902. case BABYLON.Material.LineStripDrawMode:
  10903. return this._gl.LINE_STRIP;
  10904. case BABYLON.Material.TriangleStripDrawMode:
  10905. return this._gl.TRIANGLE_STRIP;
  10906. case BABYLON.Material.TriangleFanDrawMode:
  10907. return this._gl.TRIANGLE_FAN;
  10908. default:
  10909. return this._gl.TRIANGLES;
  10910. }
  10911. };
  10912. // Shaders
  10913. Engine.prototype._releaseEffect = function (effect) {
  10914. if (this._compiledEffects[effect._key]) {
  10915. delete this._compiledEffects[effect._key];
  10916. this._deleteProgram(effect.getProgram());
  10917. }
  10918. };
  10919. Engine.prototype._deleteProgram = function (program) {
  10920. if (program) {
  10921. program.__SPECTOR_rebuildProgram = null;
  10922. if (program.transformFeedback) {
  10923. this.deleteTransformFeedback(program.transformFeedback);
  10924. program.transformFeedback = null;
  10925. }
  10926. this._gl.deleteProgram(program);
  10927. }
  10928. };
  10929. /**
  10930. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10931. * @param samplers An array of string used to represent textures
  10932. */
  10933. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10934. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10935. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10936. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10937. if (this._compiledEffects[name]) {
  10938. var compiledEffect = this._compiledEffects[name];
  10939. if (onCompiled && compiledEffect.isReady()) {
  10940. onCompiled(compiledEffect);
  10941. }
  10942. return compiledEffect;
  10943. }
  10944. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10945. effect._key = name;
  10946. this._compiledEffects[name] = effect;
  10947. return effect;
  10948. };
  10949. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10950. if (uniformsNames === void 0) { uniformsNames = []; }
  10951. if (samplers === void 0) { samplers = []; }
  10952. if (defines === void 0) { defines = ""; }
  10953. return this.createEffect({
  10954. vertex: "particles",
  10955. fragmentElement: fragmentName
  10956. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10957. };
  10958. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10959. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10960. context = context || this._gl;
  10961. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10962. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10963. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10964. };
  10965. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10966. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10967. context = context || this._gl;
  10968. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10969. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10970. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10971. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10972. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10973. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10974. return program;
  10975. };
  10976. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10977. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10978. var shaderProgram = context.createProgram();
  10979. if (!shaderProgram) {
  10980. throw new Error("Unable to create program");
  10981. }
  10982. context.attachShader(shaderProgram, vertexShader);
  10983. context.attachShader(shaderProgram, fragmentShader);
  10984. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10985. var transformFeedback = this.createTransformFeedback();
  10986. this.bindTransformFeedback(transformFeedback);
  10987. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10988. shaderProgram.transformFeedback = transformFeedback;
  10989. }
  10990. context.linkProgram(shaderProgram);
  10991. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10992. this.bindTransformFeedback(null);
  10993. }
  10994. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10995. if (!linked) {
  10996. context.validateProgram(shaderProgram);
  10997. var error = context.getProgramInfoLog(shaderProgram);
  10998. if (error) {
  10999. throw new Error(error);
  11000. }
  11001. }
  11002. context.deleteShader(vertexShader);
  11003. context.deleteShader(fragmentShader);
  11004. return shaderProgram;
  11005. };
  11006. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11007. var results = new Array();
  11008. for (var index = 0; index < uniformsNames.length; index++) {
  11009. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11010. }
  11011. return results;
  11012. };
  11013. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11014. var results = [];
  11015. for (var index = 0; index < attributesNames.length; index++) {
  11016. try {
  11017. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11018. }
  11019. catch (e) {
  11020. results.push(-1);
  11021. }
  11022. }
  11023. return results;
  11024. };
  11025. Engine.prototype.enableEffect = function (effect) {
  11026. if (!effect) {
  11027. return;
  11028. }
  11029. // Use program
  11030. this.bindSamplers(effect);
  11031. this._currentEffect = effect;
  11032. if (effect.onBind) {
  11033. effect.onBind(effect);
  11034. }
  11035. effect.onBindObservable.notifyObservers(effect);
  11036. };
  11037. Engine.prototype.setIntArray = function (uniform, array) {
  11038. if (!uniform)
  11039. return;
  11040. this._gl.uniform1iv(uniform, array);
  11041. };
  11042. Engine.prototype.setIntArray2 = function (uniform, array) {
  11043. if (!uniform || array.length % 2 !== 0)
  11044. return;
  11045. this._gl.uniform2iv(uniform, array);
  11046. };
  11047. Engine.prototype.setIntArray3 = function (uniform, array) {
  11048. if (!uniform || array.length % 3 !== 0)
  11049. return;
  11050. this._gl.uniform3iv(uniform, array);
  11051. };
  11052. Engine.prototype.setIntArray4 = function (uniform, array) {
  11053. if (!uniform || array.length % 4 !== 0)
  11054. return;
  11055. this._gl.uniform4iv(uniform, array);
  11056. };
  11057. Engine.prototype.setFloatArray = function (uniform, array) {
  11058. if (!uniform)
  11059. return;
  11060. this._gl.uniform1fv(uniform, array);
  11061. };
  11062. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11063. if (!uniform || array.length % 2 !== 0)
  11064. return;
  11065. this._gl.uniform2fv(uniform, array);
  11066. };
  11067. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11068. if (!uniform || array.length % 3 !== 0)
  11069. return;
  11070. this._gl.uniform3fv(uniform, array);
  11071. };
  11072. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11073. if (!uniform || array.length % 4 !== 0)
  11074. return;
  11075. this._gl.uniform4fv(uniform, array);
  11076. };
  11077. Engine.prototype.setArray = function (uniform, array) {
  11078. if (!uniform)
  11079. return;
  11080. this._gl.uniform1fv(uniform, array);
  11081. };
  11082. Engine.prototype.setArray2 = function (uniform, array) {
  11083. if (!uniform || array.length % 2 !== 0)
  11084. return;
  11085. this._gl.uniform2fv(uniform, array);
  11086. };
  11087. Engine.prototype.setArray3 = function (uniform, array) {
  11088. if (!uniform || array.length % 3 !== 0)
  11089. return;
  11090. this._gl.uniform3fv(uniform, array);
  11091. };
  11092. Engine.prototype.setArray4 = function (uniform, array) {
  11093. if (!uniform || array.length % 4 !== 0)
  11094. return;
  11095. this._gl.uniform4fv(uniform, array);
  11096. };
  11097. Engine.prototype.setMatrices = function (uniform, matrices) {
  11098. if (!uniform)
  11099. return;
  11100. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11101. };
  11102. Engine.prototype.setMatrix = function (uniform, matrix) {
  11103. if (!uniform)
  11104. return;
  11105. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11106. };
  11107. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11108. if (!uniform)
  11109. return;
  11110. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11111. };
  11112. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11113. if (!uniform)
  11114. return;
  11115. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11116. };
  11117. Engine.prototype.setInt = function (uniform, value) {
  11118. if (!uniform)
  11119. return;
  11120. this._gl.uniform1i(uniform, value);
  11121. };
  11122. Engine.prototype.setFloat = function (uniform, value) {
  11123. if (!uniform)
  11124. return;
  11125. this._gl.uniform1f(uniform, value);
  11126. };
  11127. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11128. if (!uniform)
  11129. return;
  11130. this._gl.uniform2f(uniform, x, y);
  11131. };
  11132. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11133. if (!uniform)
  11134. return;
  11135. this._gl.uniform3f(uniform, x, y, z);
  11136. };
  11137. Engine.prototype.setBool = function (uniform, bool) {
  11138. if (!uniform)
  11139. return;
  11140. this._gl.uniform1i(uniform, bool);
  11141. };
  11142. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11143. if (!uniform)
  11144. return;
  11145. this._gl.uniform4f(uniform, x, y, z, w);
  11146. };
  11147. Engine.prototype.setColor3 = function (uniform, color3) {
  11148. if (!uniform)
  11149. return;
  11150. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11151. };
  11152. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11153. if (!uniform)
  11154. return;
  11155. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11156. };
  11157. // States
  11158. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11159. if (zOffset === void 0) { zOffset = 0; }
  11160. if (reverseSide === void 0) { reverseSide = false; }
  11161. // Culling
  11162. if (this._depthCullingState.cull !== culling || force) {
  11163. this._depthCullingState.cull = culling;
  11164. }
  11165. // Cull face
  11166. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11167. if (this._depthCullingState.cullFace !== cullFace || force) {
  11168. this._depthCullingState.cullFace = cullFace;
  11169. }
  11170. // Z offset
  11171. this.setZOffset(zOffset);
  11172. // Front face
  11173. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11174. if (this._depthCullingState.frontFace !== frontFace || force) {
  11175. this._depthCullingState.frontFace = frontFace;
  11176. }
  11177. };
  11178. Engine.prototype.setZOffset = function (value) {
  11179. this._depthCullingState.zOffset = value;
  11180. };
  11181. Engine.prototype.getZOffset = function () {
  11182. return this._depthCullingState.zOffset;
  11183. };
  11184. Engine.prototype.setDepthBuffer = function (enable) {
  11185. this._depthCullingState.depthTest = enable;
  11186. };
  11187. Engine.prototype.getDepthWrite = function () {
  11188. return this._depthCullingState.depthMask;
  11189. };
  11190. Engine.prototype.setDepthWrite = function (enable) {
  11191. this._depthCullingState.depthMask = enable;
  11192. };
  11193. Engine.prototype.setColorWrite = function (enable) {
  11194. this._gl.colorMask(enable, enable, enable, enable);
  11195. this._colorWrite = enable;
  11196. };
  11197. Engine.prototype.getColorWrite = function () {
  11198. return this._colorWrite;
  11199. };
  11200. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11201. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11202. };
  11203. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11204. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11205. if (this._alphaMode === mode) {
  11206. return;
  11207. }
  11208. switch (mode) {
  11209. case Engine.ALPHA_DISABLE:
  11210. this._alphaState.alphaBlend = false;
  11211. break;
  11212. case Engine.ALPHA_PREMULTIPLIED:
  11213. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11214. this._alphaState.alphaBlend = true;
  11215. break;
  11216. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11217. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11218. this._alphaState.alphaBlend = true;
  11219. break;
  11220. case Engine.ALPHA_COMBINE:
  11221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11222. this._alphaState.alphaBlend = true;
  11223. break;
  11224. case Engine.ALPHA_ONEONE:
  11225. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11226. this._alphaState.alphaBlend = true;
  11227. break;
  11228. case Engine.ALPHA_ADD:
  11229. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11230. this._alphaState.alphaBlend = true;
  11231. break;
  11232. case Engine.ALPHA_SUBTRACT:
  11233. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11234. this._alphaState.alphaBlend = true;
  11235. break;
  11236. case Engine.ALPHA_MULTIPLY:
  11237. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11238. this._alphaState.alphaBlend = true;
  11239. break;
  11240. case Engine.ALPHA_MAXIMIZED:
  11241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11242. this._alphaState.alphaBlend = true;
  11243. break;
  11244. case Engine.ALPHA_INTERPOLATE:
  11245. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11246. this._alphaState.alphaBlend = true;
  11247. break;
  11248. case Engine.ALPHA_SCREENMODE:
  11249. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11250. this._alphaState.alphaBlend = true;
  11251. break;
  11252. }
  11253. if (!noDepthWriteChange) {
  11254. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11255. }
  11256. this._alphaMode = mode;
  11257. };
  11258. Engine.prototype.getAlphaMode = function () {
  11259. return this._alphaMode;
  11260. };
  11261. Engine.prototype.setAlphaTesting = function (enable) {
  11262. this._alphaTest = enable;
  11263. };
  11264. Engine.prototype.getAlphaTesting = function () {
  11265. return !!this._alphaTest;
  11266. };
  11267. // Textures
  11268. Engine.prototype.wipeCaches = function (bruteForce) {
  11269. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11270. return;
  11271. }
  11272. this._currentEffect = null;
  11273. // 6/8/2017: deltakosh: Should not be required anymore.
  11274. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11275. if (bruteForce) {
  11276. this.resetTextureCache();
  11277. this._currentProgram = null;
  11278. this._stencilState.reset();
  11279. this._depthCullingState.reset();
  11280. this.setDepthFunctionToLessOrEqual();
  11281. this._alphaState.reset();
  11282. }
  11283. this._resetVertexBufferBinding();
  11284. this._cachedIndexBuffer = null;
  11285. this._cachedEffectForVertexBuffers = null;
  11286. this._unbindVertexArrayObject();
  11287. this.bindIndexBuffer(null);
  11288. };
  11289. /**
  11290. * Set the compressed texture format to use, based on the formats you have, and the formats
  11291. * supported by the hardware / browser.
  11292. *
  11293. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11294. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11295. * to API arguments needed to compressed textures. This puts the burden on the container
  11296. * generator to house the arcane code for determining these for current & future formats.
  11297. *
  11298. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11299. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11300. *
  11301. * Note: The result of this call is not taken into account when a texture is base64.
  11302. *
  11303. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11304. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11305. *
  11306. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11307. * @returns The extension selected.
  11308. */
  11309. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11310. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11311. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11312. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11313. return this._textureFormatInUse = this._texturesSupported[i];
  11314. }
  11315. }
  11316. }
  11317. // actively set format to nothing, to allow this to be called more than once
  11318. // and possibly fail the 2nd time
  11319. this._textureFormatInUse = null;
  11320. return null;
  11321. };
  11322. Engine.prototype._createTexture = function () {
  11323. var texture = this._gl.createTexture();
  11324. if (!texture) {
  11325. throw new Error("Unable to create texture");
  11326. }
  11327. return texture;
  11328. };
  11329. /**
  11330. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11331. * @param {string} urlArg- This contains one of the following:
  11332. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11333. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11334. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11335. *
  11336. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11337. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11338. * @param {Scene} scene- Needed for loading to the correct scene.
  11339. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11340. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11341. * @param {callback} onError- Optional callback to be called upon failure.
  11342. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11343. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11344. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11345. *
  11346. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11347. */
  11348. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11349. var _this = this;
  11350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11351. if (onLoad === void 0) { onLoad = null; }
  11352. if (onError === void 0) { onError = null; }
  11353. if (buffer === void 0) { buffer = null; }
  11354. if (fallBack === void 0) { fallBack = null; }
  11355. if (format === void 0) { format = null; }
  11356. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11357. var fromData = url.substr(0, 5) === "data:";
  11358. var fromBlob = url.substr(0, 5) === "blob:";
  11359. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11360. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11361. // establish the file extension, if possible
  11362. var lastDot = url.lastIndexOf('.');
  11363. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11364. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11365. var isTGA = (extension === ".tga");
  11366. // determine if a ktx file should be substituted
  11367. var isKTX = false;
  11368. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11369. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11370. isKTX = true;
  11371. }
  11372. if (scene) {
  11373. scene._addPendingData(texture);
  11374. }
  11375. texture.url = url;
  11376. texture.generateMipMaps = !noMipmap;
  11377. texture.samplingMode = samplingMode;
  11378. texture.invertY = invertY;
  11379. if (!this._doNotHandleContextLost) {
  11380. // Keep a link to the buffer only if we plan to handle context lost
  11381. texture._buffer = buffer;
  11382. }
  11383. var onLoadObserver = null;
  11384. if (onLoad && !fallBack) {
  11385. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11386. }
  11387. if (!fallBack)
  11388. this._internalTexturesCache.push(texture);
  11389. var onerror = function (message, exception) {
  11390. if (scene) {
  11391. scene._removePendingData(texture);
  11392. }
  11393. if (onLoadObserver) {
  11394. texture.onLoadedObservable.remove(onLoadObserver);
  11395. }
  11396. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11397. if (isKTX) {
  11398. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11399. }
  11400. else if (BABYLON.Tools.UseFallbackTexture) {
  11401. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11402. }
  11403. if (onError) {
  11404. onError(message || "Unknown error", exception);
  11405. }
  11406. };
  11407. var callback = null;
  11408. // processing for non-image formats
  11409. if (isKTX || isTGA || isDDS) {
  11410. if (isKTX) {
  11411. callback = function (data) {
  11412. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11413. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11414. ktx.uploadLevels(_this._gl, !noMipmap);
  11415. return false;
  11416. }, samplingMode);
  11417. };
  11418. }
  11419. else if (isTGA) {
  11420. callback = function (arrayBuffer) {
  11421. var data = new Uint8Array(arrayBuffer);
  11422. var header = BABYLON.TGATools.GetTGAHeader(data);
  11423. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11424. BABYLON.TGATools.UploadContent(_this._gl, data);
  11425. return false;
  11426. }, samplingMode);
  11427. };
  11428. }
  11429. else if (isDDS) {
  11430. callback = function (data) {
  11431. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11432. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11433. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11434. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11435. return false;
  11436. }, samplingMode);
  11437. };
  11438. }
  11439. if (!buffer) {
  11440. this._loadFile(url, function (data) {
  11441. if (callback) {
  11442. callback(data);
  11443. }
  11444. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11445. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11446. });
  11447. }
  11448. else {
  11449. if (callback) {
  11450. callback(buffer);
  11451. }
  11452. }
  11453. // image format processing
  11454. }
  11455. else {
  11456. var onload = function (img) {
  11457. if (fromBlob && !_this._doNotHandleContextLost) {
  11458. // We need to store the image if we need to rebuild the texture
  11459. // in case of a webgl context lost
  11460. texture._buffer = img;
  11461. }
  11462. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11463. var gl = _this._gl;
  11464. var isPot = (img.width === potWidth && img.height === potHeight);
  11465. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11466. if (isPot) {
  11467. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11468. return false;
  11469. }
  11470. // Using shaders to rescale because canvas.drawImage is lossy
  11471. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11472. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11473. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11478. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11479. _this._releaseTexture(source);
  11480. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11481. continuationCallback();
  11482. });
  11483. return true;
  11484. }, samplingMode);
  11485. };
  11486. if (!fromData || isBase64)
  11487. if (buffer instanceof HTMLImageElement) {
  11488. onload(buffer);
  11489. }
  11490. else {
  11491. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11492. }
  11493. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11494. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11495. else
  11496. onload(buffer);
  11497. }
  11498. return texture;
  11499. };
  11500. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11501. var _this = this;
  11502. var rtt = this.createRenderTargetTexture({
  11503. width: destination.width,
  11504. height: destination.height,
  11505. }, {
  11506. generateMipMaps: false,
  11507. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11508. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11509. generateDepthBuffer: false,
  11510. generateStencilBuffer: false
  11511. });
  11512. if (!this._rescalePostProcess) {
  11513. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11514. }
  11515. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11516. _this._rescalePostProcess.onApply = function (effect) {
  11517. effect._bindTexture("textureSampler", source);
  11518. };
  11519. var hostingScene = scene;
  11520. if (!hostingScene) {
  11521. hostingScene = _this.scenes[_this.scenes.length - 1];
  11522. }
  11523. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11524. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11525. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11526. _this.unBindFramebuffer(rtt);
  11527. _this._releaseTexture(rtt);
  11528. if (onComplete) {
  11529. onComplete();
  11530. }
  11531. });
  11532. };
  11533. Engine.prototype._getInternalFormat = function (format) {
  11534. var internalFormat = this._gl.RGBA;
  11535. switch (format) {
  11536. case Engine.TEXTUREFORMAT_ALPHA:
  11537. internalFormat = this._gl.ALPHA;
  11538. break;
  11539. case Engine.TEXTUREFORMAT_LUMINANCE:
  11540. internalFormat = this._gl.LUMINANCE;
  11541. break;
  11542. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11543. internalFormat = this._gl.LUMINANCE_ALPHA;
  11544. break;
  11545. case Engine.TEXTUREFORMAT_RGB:
  11546. internalFormat = this._gl.RGB;
  11547. break;
  11548. case Engine.TEXTUREFORMAT_RGBA:
  11549. internalFormat = this._gl.RGBA;
  11550. break;
  11551. }
  11552. return internalFormat;
  11553. };
  11554. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11555. if (compression === void 0) { compression = null; }
  11556. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11557. if (!texture) {
  11558. return;
  11559. }
  11560. var internalFormat = this._getInternalFormat(format);
  11561. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11562. var textureType = this._getWebGLTextureType(type);
  11563. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11564. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11565. if (!this._doNotHandleContextLost) {
  11566. texture._bufferView = data;
  11567. texture.format = format;
  11568. texture.type = type;
  11569. texture.invertY = invertY;
  11570. texture._compression = compression;
  11571. }
  11572. if (texture.width % 4 !== 0) {
  11573. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11574. }
  11575. if (compression && data) {
  11576. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11577. }
  11578. else {
  11579. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11580. }
  11581. if (texture.generateMipMaps) {
  11582. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11583. }
  11584. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11585. // this.resetTextureCache();
  11586. texture.isReady = true;
  11587. };
  11588. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11589. if (compression === void 0) { compression = null; }
  11590. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11591. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11592. texture.baseWidth = width;
  11593. texture.baseHeight = height;
  11594. texture.width = width;
  11595. texture.height = height;
  11596. texture.format = format;
  11597. texture.generateMipMaps = generateMipMaps;
  11598. texture.samplingMode = samplingMode;
  11599. texture.invertY = invertY;
  11600. texture._compression = compression;
  11601. texture.type = type;
  11602. if (!this._doNotHandleContextLost) {
  11603. texture._bufferView = data;
  11604. }
  11605. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11607. // Filters
  11608. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11609. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11611. if (generateMipMaps) {
  11612. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11613. }
  11614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11615. this._internalTexturesCache.push(texture);
  11616. return texture;
  11617. };
  11618. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11619. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11620. texture.baseWidth = width;
  11621. texture.baseHeight = height;
  11622. if (generateMipMaps) {
  11623. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11624. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11625. }
  11626. // this.resetTextureCache();
  11627. texture.width = width;
  11628. texture.height = height;
  11629. texture.isReady = false;
  11630. texture.generateMipMaps = generateMipMaps;
  11631. texture.samplingMode = samplingMode;
  11632. this.updateTextureSamplingMode(samplingMode, texture);
  11633. this._internalTexturesCache.push(texture);
  11634. return texture;
  11635. };
  11636. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11637. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11638. if (texture.isCube) {
  11639. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11640. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11641. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11642. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11643. }
  11644. else if (texture.is3D) {
  11645. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11646. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11647. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11648. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11649. }
  11650. else {
  11651. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11653. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11654. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11655. }
  11656. texture.samplingMode = samplingMode;
  11657. };
  11658. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11659. if (premulAlpha === void 0) { premulAlpha = false; }
  11660. if (!texture) {
  11661. return;
  11662. }
  11663. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11664. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11665. if (premulAlpha) {
  11666. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11667. }
  11668. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11669. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11670. if (texture.generateMipMaps) {
  11671. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11672. }
  11673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11674. if (premulAlpha) {
  11675. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11676. }
  11677. texture.isReady = true;
  11678. };
  11679. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11680. if (!texture || texture._isDisabled) {
  11681. return;
  11682. }
  11683. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11684. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11685. try {
  11686. // Testing video texture support
  11687. if (this._videoTextureSupported === undefined) {
  11688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11689. if (this._gl.getError() !== 0) {
  11690. this._videoTextureSupported = false;
  11691. }
  11692. else {
  11693. this._videoTextureSupported = true;
  11694. }
  11695. }
  11696. // Copy video through the current working canvas if video texture is not supported
  11697. if (!this._videoTextureSupported) {
  11698. if (!texture._workingCanvas) {
  11699. texture._workingCanvas = document.createElement("canvas");
  11700. var context = texture._workingCanvas.getContext("2d");
  11701. if (!context) {
  11702. throw new Error("Unable to get 2d context");
  11703. }
  11704. texture._workingContext = context;
  11705. texture._workingCanvas.width = texture.width;
  11706. texture._workingCanvas.height = texture.height;
  11707. }
  11708. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11709. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11710. }
  11711. else {
  11712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11713. }
  11714. if (texture.generateMipMaps) {
  11715. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11716. }
  11717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11718. // this.resetTextureCache();
  11719. texture.isReady = true;
  11720. }
  11721. catch (ex) {
  11722. // Something unexpected
  11723. // Let's disable the texture
  11724. texture._isDisabled = true;
  11725. }
  11726. };
  11727. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11728. var fullOptions = new RenderTargetCreationOptions();
  11729. if (options !== undefined && typeof options === "object") {
  11730. fullOptions.generateMipMaps = options.generateMipMaps;
  11731. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11732. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11733. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11734. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11735. }
  11736. else {
  11737. fullOptions.generateMipMaps = options;
  11738. fullOptions.generateDepthBuffer = true;
  11739. fullOptions.generateStencilBuffer = false;
  11740. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11741. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11742. }
  11743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11744. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11745. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11746. }
  11747. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11748. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11749. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11750. }
  11751. var gl = this._gl;
  11752. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11753. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11754. var width = size.width || size;
  11755. var height = size.height || size;
  11756. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11757. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11758. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11759. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11760. }
  11761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11765. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11766. // Create the framebuffer
  11767. var framebuffer = gl.createFramebuffer();
  11768. this.bindUnboundFramebuffer(framebuffer);
  11769. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11770. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11771. if (fullOptions.generateMipMaps) {
  11772. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11773. }
  11774. // Unbind
  11775. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11776. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11777. this.bindUnboundFramebuffer(null);
  11778. texture._framebuffer = framebuffer;
  11779. texture.baseWidth = width;
  11780. texture.baseHeight = height;
  11781. texture.width = width;
  11782. texture.height = height;
  11783. texture.isReady = true;
  11784. texture.samples = 1;
  11785. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11786. texture.samplingMode = fullOptions.samplingMode;
  11787. texture.type = fullOptions.type;
  11788. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11789. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11790. // this.resetTextureCache();
  11791. this._internalTexturesCache.push(texture);
  11792. return texture;
  11793. };
  11794. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11795. var generateMipMaps = false;
  11796. var generateDepthBuffer = true;
  11797. var generateStencilBuffer = false;
  11798. var generateDepthTexture = false;
  11799. var textureCount = 1;
  11800. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11801. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11802. var types = [], samplingModes = [];
  11803. if (options !== undefined) {
  11804. generateMipMaps = options.generateMipMaps;
  11805. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11806. generateStencilBuffer = options.generateStencilBuffer;
  11807. generateDepthTexture = options.generateDepthTexture;
  11808. textureCount = options.textureCount || 1;
  11809. if (options.types) {
  11810. types = options.types;
  11811. }
  11812. if (options.samplingModes) {
  11813. samplingModes = options.samplingModes;
  11814. }
  11815. }
  11816. var gl = this._gl;
  11817. // Create the framebuffer
  11818. var framebuffer = gl.createFramebuffer();
  11819. this.bindUnboundFramebuffer(framebuffer);
  11820. var width = size.width || size;
  11821. var height = size.height || size;
  11822. var textures = [];
  11823. var attachments = [];
  11824. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11825. for (var i = 0; i < textureCount; i++) {
  11826. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11827. var type = types[i] || defaultType;
  11828. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11829. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11830. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11831. }
  11832. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11833. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11834. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11835. }
  11836. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11837. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11838. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11839. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11840. }
  11841. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11842. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11843. textures.push(texture);
  11844. attachments.push(attachment);
  11845. gl.activeTexture(gl["TEXTURE" + i]);
  11846. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11847. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11851. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11852. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11853. if (generateMipMaps) {
  11854. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11855. }
  11856. // Unbind
  11857. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11858. texture._framebuffer = framebuffer;
  11859. texture._depthStencilBuffer = depthStencilBuffer;
  11860. texture.baseWidth = width;
  11861. texture.baseHeight = height;
  11862. texture.width = width;
  11863. texture.height = height;
  11864. texture.isReady = true;
  11865. texture.samples = 1;
  11866. texture.generateMipMaps = generateMipMaps;
  11867. texture.samplingMode = samplingMode;
  11868. texture.type = type;
  11869. texture._generateDepthBuffer = generateDepthBuffer;
  11870. texture._generateStencilBuffer = generateStencilBuffer;
  11871. texture._attachments = attachments;
  11872. this._internalTexturesCache.push(texture);
  11873. }
  11874. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11875. // Depth texture
  11876. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11877. gl.activeTexture(gl.TEXTURE0);
  11878. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11883. 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);
  11884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11885. depthTexture._framebuffer = framebuffer;
  11886. depthTexture.baseWidth = width;
  11887. depthTexture.baseHeight = height;
  11888. depthTexture.width = width;
  11889. depthTexture.height = height;
  11890. depthTexture.isReady = true;
  11891. depthTexture.samples = 1;
  11892. depthTexture.generateMipMaps = generateMipMaps;
  11893. depthTexture.samplingMode = gl.NEAREST;
  11894. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11895. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11896. textures.push(depthTexture);
  11897. this._internalTexturesCache.push(depthTexture);
  11898. }
  11899. gl.drawBuffers(attachments);
  11900. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11901. this.bindUnboundFramebuffer(null);
  11902. this.resetTextureCache();
  11903. return textures;
  11904. };
  11905. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11906. if (samples === void 0) { samples = 1; }
  11907. var depthStencilBuffer = null;
  11908. var gl = this._gl;
  11909. // Create the depth/stencil buffer
  11910. if (generateStencilBuffer) {
  11911. depthStencilBuffer = gl.createRenderbuffer();
  11912. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11913. if (samples > 1) {
  11914. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11915. }
  11916. else {
  11917. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11918. }
  11919. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11920. }
  11921. else if (generateDepthBuffer) {
  11922. depthStencilBuffer = gl.createRenderbuffer();
  11923. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11924. if (samples > 1) {
  11925. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11926. }
  11927. else {
  11928. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11929. }
  11930. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11931. }
  11932. return depthStencilBuffer;
  11933. };
  11934. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11935. if (this.webGLVersion < 2 || !texture) {
  11936. return 1;
  11937. }
  11938. if (texture.samples === samples) {
  11939. return samples;
  11940. }
  11941. var gl = this._gl;
  11942. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11943. // Dispose previous render buffers
  11944. if (texture._depthStencilBuffer) {
  11945. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11946. texture._depthStencilBuffer = null;
  11947. }
  11948. if (texture._MSAAFramebuffer) {
  11949. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11950. texture._MSAAFramebuffer = null;
  11951. }
  11952. if (texture._MSAARenderBuffer) {
  11953. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11954. texture._MSAARenderBuffer = null;
  11955. }
  11956. if (samples > 1) {
  11957. var framebuffer = gl.createFramebuffer();
  11958. if (!framebuffer) {
  11959. throw new Error("Unable to create multi sampled framebuffer");
  11960. }
  11961. texture._MSAAFramebuffer = framebuffer;
  11962. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11963. var colorRenderbuffer = gl.createRenderbuffer();
  11964. if (!colorRenderbuffer) {
  11965. throw new Error("Unable to create multi sampled framebuffer");
  11966. }
  11967. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11968. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11969. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11970. texture._MSAARenderBuffer = colorRenderbuffer;
  11971. }
  11972. else {
  11973. this.bindUnboundFramebuffer(texture._framebuffer);
  11974. }
  11975. texture.samples = samples;
  11976. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11977. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11978. this.bindUnboundFramebuffer(null);
  11979. return samples;
  11980. };
  11981. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11982. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11983. return 1;
  11984. }
  11985. if (textures[0].samples === samples) {
  11986. return samples;
  11987. }
  11988. var gl = this._gl;
  11989. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11990. // Dispose previous render buffers
  11991. if (textures[0]._depthStencilBuffer) {
  11992. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11993. textures[0]._depthStencilBuffer = null;
  11994. }
  11995. if (textures[0]._MSAAFramebuffer) {
  11996. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11997. textures[0]._MSAAFramebuffer = null;
  11998. }
  11999. for (var i = 0; i < textures.length; i++) {
  12000. if (textures[i]._MSAARenderBuffer) {
  12001. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12002. textures[i]._MSAARenderBuffer = null;
  12003. }
  12004. }
  12005. if (samples > 1) {
  12006. var framebuffer = gl.createFramebuffer();
  12007. if (!framebuffer) {
  12008. throw new Error("Unable to create multi sampled framebuffer");
  12009. }
  12010. this.bindUnboundFramebuffer(framebuffer);
  12011. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12012. var attachments = [];
  12013. for (var i = 0; i < textures.length; i++) {
  12014. var texture = textures[i];
  12015. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12016. var colorRenderbuffer = gl.createRenderbuffer();
  12017. if (!colorRenderbuffer) {
  12018. throw new Error("Unable to create multi sampled framebuffer");
  12019. }
  12020. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12021. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12022. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12023. texture._MSAAFramebuffer = framebuffer;
  12024. texture._MSAARenderBuffer = colorRenderbuffer;
  12025. texture.samples = samples;
  12026. texture._depthStencilBuffer = depthStencilBuffer;
  12027. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12028. attachments.push(attachment);
  12029. }
  12030. gl.drawBuffers(attachments);
  12031. }
  12032. else {
  12033. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12034. }
  12035. this.bindUnboundFramebuffer(null);
  12036. return samples;
  12037. };
  12038. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12039. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12040. };
  12041. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12042. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12043. };
  12044. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12045. var gl = this._gl;
  12046. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12047. var generateMipMaps = true;
  12048. var generateDepthBuffer = true;
  12049. var generateStencilBuffer = false;
  12050. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12051. if (options !== undefined) {
  12052. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12053. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12054. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12055. if (options.samplingMode !== undefined) {
  12056. samplingMode = options.samplingMode;
  12057. }
  12058. }
  12059. texture.isCube = true;
  12060. texture.generateMipMaps = generateMipMaps;
  12061. texture.samples = 1;
  12062. texture.samplingMode = samplingMode;
  12063. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12064. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12065. for (var face = 0; face < 6; face++) {
  12066. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12067. }
  12068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12072. // Create the framebuffer
  12073. var framebuffer = gl.createFramebuffer();
  12074. this.bindUnboundFramebuffer(framebuffer);
  12075. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12076. // Mipmaps
  12077. if (texture.generateMipMaps) {
  12078. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12079. }
  12080. // Unbind
  12081. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12082. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12083. this.bindUnboundFramebuffer(null);
  12084. texture._framebuffer = framebuffer;
  12085. texture.width = size;
  12086. texture.height = size;
  12087. texture.isReady = true;
  12088. //this.resetTextureCache();
  12089. this._internalTexturesCache.push(texture);
  12090. return texture;
  12091. };
  12092. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12093. var _this = this;
  12094. if (onLoad === void 0) { onLoad = null; }
  12095. if (onError === void 0) { onError = null; }
  12096. if (forcedExtension === void 0) { forcedExtension = null; }
  12097. var callback = function (loadData) {
  12098. if (!loadData) {
  12099. if (onLoad) {
  12100. onLoad(null);
  12101. }
  12102. return;
  12103. }
  12104. var texture = loadData.texture;
  12105. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12106. texture._lodGenerationScale = scale;
  12107. texture._lodGenerationOffset = offset;
  12108. if (_this._caps.textureLOD) {
  12109. // Do not add extra process if texture lod is supported.
  12110. if (onLoad) {
  12111. onLoad(texture);
  12112. }
  12113. return;
  12114. }
  12115. var mipSlices = 3;
  12116. var gl = _this._gl;
  12117. var width = loadData.width;
  12118. if (!width) {
  12119. return;
  12120. }
  12121. var textures = [];
  12122. for (var i = 0; i < mipSlices; i++) {
  12123. //compute LOD from even spacing in smoothness (matching shader calculation)
  12124. var smoothness = i / (mipSlices - 1);
  12125. var roughness = 1 - smoothness;
  12126. var minLODIndex = offset; // roughness = 0
  12127. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12128. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12129. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12130. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12131. glTextureFromLod.isCube = true;
  12132. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12137. if (loadData.isDDS) {
  12138. var info = loadData.info;
  12139. var data = loadData.data;
  12140. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12141. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12142. }
  12143. else {
  12144. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12145. }
  12146. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12147. // Wrap in a base texture for easy binding.
  12148. var lodTexture = new BABYLON.BaseTexture(scene);
  12149. lodTexture.isCube = true;
  12150. lodTexture._texture = glTextureFromLod;
  12151. glTextureFromLod.isReady = true;
  12152. textures.push(lodTexture);
  12153. }
  12154. texture._lodTextureHigh = textures[2];
  12155. texture._lodTextureMid = textures[1];
  12156. texture._lodTextureLow = textures[0];
  12157. if (onLoad) {
  12158. onLoad(texture);
  12159. }
  12160. };
  12161. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12162. };
  12163. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12164. var _this = this;
  12165. if (onLoad === void 0) { onLoad = null; }
  12166. if (onError === void 0) { onError = null; }
  12167. if (forcedExtension === void 0) { forcedExtension = null; }
  12168. var gl = this._gl;
  12169. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12170. texture.isCube = true;
  12171. texture.url = rootUrl;
  12172. texture.generateMipMaps = !noMipmap;
  12173. if (!this._doNotHandleContextLost) {
  12174. texture._extension = forcedExtension;
  12175. texture._files = files;
  12176. }
  12177. var isKTX = false;
  12178. var isDDS = false;
  12179. var lastDot = rootUrl.lastIndexOf('.');
  12180. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12181. if (this._textureFormatInUse) {
  12182. extension = this._textureFormatInUse;
  12183. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12184. isKTX = true;
  12185. }
  12186. else {
  12187. isDDS = (extension === ".dds");
  12188. }
  12189. var onerror = function (request, exception) {
  12190. if (onError && request) {
  12191. onError(request.status + " " + request.statusText, exception);
  12192. }
  12193. };
  12194. if (isKTX) {
  12195. this._loadFile(rootUrl, function (data) {
  12196. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12197. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12198. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12199. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12200. ktx.uploadLevels(_this._gl, !noMipmap);
  12201. _this.setCubeMapTextureParams(gl, loadMipmap);
  12202. texture.width = ktx.pixelWidth;
  12203. texture.height = ktx.pixelHeight;
  12204. texture.isReady = true;
  12205. }, undefined, undefined, true, onerror);
  12206. }
  12207. else if (isDDS) {
  12208. if (files && files.length === 6) {
  12209. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12210. var info;
  12211. var loadMipmap = false;
  12212. var width = 0;
  12213. for (var index = 0; index < imgs.length; index++) {
  12214. var data = imgs[index];
  12215. info = BABYLON.DDSTools.GetDDSInfo(data);
  12216. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12217. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12218. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12219. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12220. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12221. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12222. }
  12223. texture.width = info.width;
  12224. texture.height = info.height;
  12225. texture.type = info.textureType;
  12226. width = info.width;
  12227. }
  12228. _this.setCubeMapTextureParams(gl, loadMipmap);
  12229. texture.isReady = true;
  12230. if (onLoad) {
  12231. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12232. }
  12233. }, files, onError);
  12234. }
  12235. else {
  12236. this._loadFile(rootUrl, function (data) {
  12237. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12238. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12239. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12240. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12241. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12242. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12243. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12244. }
  12245. _this.setCubeMapTextureParams(gl, loadMipmap);
  12246. texture.width = info.width;
  12247. texture.height = info.height;
  12248. texture.isReady = true;
  12249. texture.type = info.textureType;
  12250. if (onLoad) {
  12251. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12252. }
  12253. }, undefined, undefined, true, onerror);
  12254. }
  12255. }
  12256. else {
  12257. if (!files) {
  12258. throw new Error("Cannot load cubemap because files were not defined");
  12259. }
  12260. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12261. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12262. var height = width;
  12263. _this._prepareWorkingCanvas();
  12264. if (!_this._workingCanvas || !_this._workingContext) {
  12265. return;
  12266. }
  12267. _this._workingCanvas.width = width;
  12268. _this._workingCanvas.height = height;
  12269. var faces = [
  12270. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12271. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12272. ];
  12273. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12274. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12275. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12276. for (var index = 0; index < faces.length; index++) {
  12277. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12278. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12279. }
  12280. if (!noMipmap) {
  12281. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12282. }
  12283. _this.setCubeMapTextureParams(gl, !noMipmap);
  12284. texture.width = width;
  12285. texture.height = height;
  12286. texture.isReady = true;
  12287. if (format) {
  12288. texture.format = format;
  12289. }
  12290. texture.onLoadedObservable.notifyObservers(texture);
  12291. texture.onLoadedObservable.clear();
  12292. if (onLoad) {
  12293. onLoad();
  12294. }
  12295. }, files, onError);
  12296. }
  12297. this._internalTexturesCache.push(texture);
  12298. return texture;
  12299. };
  12300. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12305. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12306. // this.resetTextureCache();
  12307. };
  12308. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12309. if (compression === void 0) { compression = null; }
  12310. if (level === void 0) { level = 0; }
  12311. texture._bufferViewArray = data;
  12312. texture.format = format;
  12313. texture.type = type;
  12314. texture.invertY = invertY;
  12315. texture._compression = compression;
  12316. var gl = this._gl;
  12317. var textureType = this._getWebGLTextureType(type);
  12318. var internalFormat = this._getInternalFormat(format);
  12319. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12320. var needConversion = false;
  12321. if (internalFormat === gl.RGB) {
  12322. internalFormat = gl.RGBA;
  12323. needConversion = true;
  12324. }
  12325. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12326. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12327. if (texture.width % 4 !== 0) {
  12328. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12329. }
  12330. // Data are known to be in +X +Y +Z -X -Y -Z
  12331. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12332. var faceData = data[faceIndex];
  12333. if (compression) {
  12334. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12335. }
  12336. else {
  12337. if (needConversion) {
  12338. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12339. }
  12340. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12341. }
  12342. }
  12343. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12344. if (isPot && texture.generateMipMaps && level === 0) {
  12345. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12346. }
  12347. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12348. // this.resetTextureCache();
  12349. texture.isReady = true;
  12350. };
  12351. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12352. if (compression === void 0) { compression = null; }
  12353. var gl = this._gl;
  12354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12355. texture.isCube = true;
  12356. texture.generateMipMaps = generateMipMaps;
  12357. texture.format = format;
  12358. texture.type = type;
  12359. if (!this._doNotHandleContextLost) {
  12360. texture._bufferViewArray = data;
  12361. }
  12362. var textureType = this._getWebGLTextureType(type);
  12363. var internalFormat = this._getInternalFormat(format);
  12364. if (internalFormat === gl.RGB) {
  12365. internalFormat = gl.RGBA;
  12366. }
  12367. var width = size;
  12368. var height = width;
  12369. texture.width = width;
  12370. texture.height = height;
  12371. // Double check on POT to generate Mips.
  12372. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12373. if (!isPot) {
  12374. generateMipMaps = false;
  12375. }
  12376. // Upload data if needed. The texture won't be ready until then.
  12377. if (data) {
  12378. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12379. }
  12380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12381. // Filters
  12382. if (data && generateMipMaps) {
  12383. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12384. }
  12385. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12388. }
  12389. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12392. }
  12393. else {
  12394. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12397. }
  12398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12401. return texture;
  12402. };
  12403. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12404. var _this = this;
  12405. if (onLoad === void 0) { onLoad = null; }
  12406. if (onError === void 0) { onError = null; }
  12407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12408. if (invertY === void 0) { invertY = false; }
  12409. var gl = this._gl;
  12410. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12411. scene._addPendingData(texture);
  12412. texture.url = url;
  12413. this._internalTexturesCache.push(texture);
  12414. var onerror = function (request, exception) {
  12415. scene._removePendingData(texture);
  12416. if (onError && request) {
  12417. onError(request.status + " " + request.statusText, exception);
  12418. }
  12419. };
  12420. var internalCallback = function (data) {
  12421. var width = texture.width;
  12422. var faceDataArrays = callback(data);
  12423. if (!faceDataArrays) {
  12424. return;
  12425. }
  12426. if (mipmmapGenerator) {
  12427. var textureType = _this._getWebGLTextureType(type);
  12428. var internalFormat = _this._getInternalFormat(format);
  12429. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12430. var needConversion = false;
  12431. if (internalFormat === gl.RGB) {
  12432. internalFormat = gl.RGBA;
  12433. needConversion = true;
  12434. }
  12435. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12436. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12437. var mipData = mipmmapGenerator(faceDataArrays);
  12438. for (var level = 0; level < mipData.length; level++) {
  12439. var mipSize = width >> level;
  12440. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12441. var mipFaceData = mipData[level][faceIndex];
  12442. if (needConversion) {
  12443. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12444. }
  12445. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12446. }
  12447. }
  12448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12449. }
  12450. else {
  12451. texture.generateMipMaps = !noMipmap;
  12452. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12453. }
  12454. texture.isReady = true;
  12455. // this.resetTextureCache();
  12456. scene._removePendingData(texture);
  12457. if (onLoad) {
  12458. onLoad();
  12459. }
  12460. };
  12461. this._loadFile(url, function (data) {
  12462. internalCallback(data);
  12463. }, undefined, scene.database, true, onerror);
  12464. return texture;
  12465. };
  12466. ;
  12467. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12468. if (compression === void 0) { compression = null; }
  12469. var internalFormat = this._getInternalFormat(format);
  12470. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12471. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12472. if (!this._doNotHandleContextLost) {
  12473. texture._bufferView = data;
  12474. texture.format = format;
  12475. texture.invertY = invertY;
  12476. texture._compression = compression;
  12477. }
  12478. if (texture.width % 4 !== 0) {
  12479. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12480. }
  12481. if (compression && data) {
  12482. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12483. }
  12484. else {
  12485. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12486. }
  12487. if (texture.generateMipMaps) {
  12488. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12489. }
  12490. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12491. // this.resetTextureCache();
  12492. texture.isReady = true;
  12493. };
  12494. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12495. if (compression === void 0) { compression = null; }
  12496. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12497. texture.baseWidth = width;
  12498. texture.baseHeight = height;
  12499. texture.baseDepth = depth;
  12500. texture.width = width;
  12501. texture.height = height;
  12502. texture.depth = depth;
  12503. texture.format = format;
  12504. texture.generateMipMaps = generateMipMaps;
  12505. texture.samplingMode = samplingMode;
  12506. texture.is3D = true;
  12507. if (!this._doNotHandleContextLost) {
  12508. texture._bufferView = data;
  12509. }
  12510. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12511. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12512. // Filters
  12513. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12514. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12515. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12516. if (generateMipMaps) {
  12517. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12518. }
  12519. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12520. this._internalTexturesCache.push(texture);
  12521. return texture;
  12522. };
  12523. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12524. var gl = this._gl;
  12525. if (!gl) {
  12526. return;
  12527. }
  12528. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12531. if (!noMipmap && !isCompressed) {
  12532. gl.generateMipmap(gl.TEXTURE_2D);
  12533. }
  12534. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12535. // this.resetTextureCache();
  12536. if (scene) {
  12537. scene._removePendingData(texture);
  12538. }
  12539. texture.onLoadedObservable.notifyObservers(texture);
  12540. texture.onLoadedObservable.clear();
  12541. };
  12542. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12543. var _this = this;
  12544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12545. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12546. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12547. var gl = this._gl;
  12548. if (!gl) {
  12549. return;
  12550. }
  12551. if (!texture._webGLTexture) {
  12552. // this.resetTextureCache();
  12553. if (scene) {
  12554. scene._removePendingData(texture);
  12555. }
  12556. return;
  12557. }
  12558. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12559. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12560. texture.baseWidth = width;
  12561. texture.baseHeight = height;
  12562. texture.width = potWidth;
  12563. texture.height = potHeight;
  12564. texture.isReady = true;
  12565. if (processFunction(potWidth, potHeight, function () {
  12566. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12567. })) {
  12568. // Returning as texture needs extra async steps
  12569. return;
  12570. }
  12571. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12572. };
  12573. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12574. // Create new RGBA data container.
  12575. var rgbaData;
  12576. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12577. rgbaData = new Float32Array(width * height * 4);
  12578. }
  12579. else {
  12580. rgbaData = new Uint32Array(width * height * 4);
  12581. }
  12582. // Convert each pixel.
  12583. for (var x = 0; x < width; x++) {
  12584. for (var y = 0; y < height; y++) {
  12585. var index = (y * width + x) * 3;
  12586. var newIndex = (y * width + x) * 4;
  12587. // Map Old Value to new value.
  12588. rgbaData[newIndex + 0] = rgbData[index + 0];
  12589. rgbaData[newIndex + 1] = rgbData[index + 1];
  12590. rgbaData[newIndex + 2] = rgbData[index + 2];
  12591. // Add fully opaque alpha channel.
  12592. rgbaData[newIndex + 3] = 1;
  12593. }
  12594. }
  12595. return rgbaData;
  12596. };
  12597. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12598. var gl = this._gl;
  12599. if (texture._framebuffer) {
  12600. gl.deleteFramebuffer(texture._framebuffer);
  12601. texture._framebuffer = null;
  12602. }
  12603. if (texture._depthStencilBuffer) {
  12604. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12605. texture._depthStencilBuffer = null;
  12606. }
  12607. if (texture._MSAAFramebuffer) {
  12608. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12609. texture._MSAAFramebuffer = null;
  12610. }
  12611. if (texture._MSAARenderBuffer) {
  12612. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12613. texture._MSAARenderBuffer = null;
  12614. }
  12615. };
  12616. Engine.prototype._releaseTexture = function (texture) {
  12617. var gl = this._gl;
  12618. this._releaseFramebufferObjects(texture);
  12619. gl.deleteTexture(texture._webGLTexture);
  12620. // Unbind channels
  12621. this.unbindAllTextures();
  12622. var index = this._internalTexturesCache.indexOf(texture);
  12623. if (index !== -1) {
  12624. this._internalTexturesCache.splice(index, 1);
  12625. }
  12626. // Integrated fixed lod samplers.
  12627. if (texture._lodTextureHigh) {
  12628. texture._lodTextureHigh.dispose();
  12629. }
  12630. if (texture._lodTextureMid) {
  12631. texture._lodTextureMid.dispose();
  12632. }
  12633. if (texture._lodTextureLow) {
  12634. texture._lodTextureLow.dispose();
  12635. }
  12636. };
  12637. Engine.prototype.setProgram = function (program) {
  12638. if (this._currentProgram !== program) {
  12639. this._gl.useProgram(program);
  12640. this._currentProgram = program;
  12641. }
  12642. };
  12643. Engine.prototype.bindSamplers = function (effect) {
  12644. this.setProgram(effect.getProgram());
  12645. var samplers = effect.getSamplers();
  12646. for (var index = 0; index < samplers.length; index++) {
  12647. var uniform = effect.getUniform(samplers[index]);
  12648. if (uniform) {
  12649. this._boundUniforms[index] = uniform;
  12650. }
  12651. }
  12652. this._currentEffect = null;
  12653. };
  12654. Engine.prototype._activateTextureChannel = function (channel) {
  12655. if (this._activeChannel !== channel && channel > -1) {
  12656. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12657. this._activeChannel = channel;
  12658. }
  12659. };
  12660. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12661. var index = this._boundTexturesStack.indexOf(internalTexture);
  12662. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12663. this._boundTexturesStack.splice(index, 1);
  12664. this._boundTexturesStack.push(internalTexture);
  12665. }
  12666. };
  12667. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12668. var currentSlot = internalTexture._designatedSlot;
  12669. internalTexture._designatedSlot = -1;
  12670. var index = this._boundTexturesStack.indexOf(internalTexture);
  12671. if (index > -1) {
  12672. this._boundTexturesStack.splice(index, 1);
  12673. if (currentSlot > -1) {
  12674. this._boundTexturesCache[currentSlot] = null;
  12675. this._nextFreeTextureSlots.push(currentSlot);
  12676. }
  12677. }
  12678. return currentSlot;
  12679. };
  12680. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12681. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12682. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12683. var isTextureForRendering = texture && texture._initialSlot > -1;
  12684. if (currentTextureBound !== texture) {
  12685. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12686. this._removeDesignatedSlot(currentTextureBound);
  12687. }
  12688. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12689. if (this._activeChannel >= 0) {
  12690. this._boundTexturesCache[this._activeChannel] = texture;
  12691. if (isTextureForRendering && !this.disableTextureBindingOptimization) {
  12692. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12693. if (slotIndex > -1) {
  12694. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12695. }
  12696. this._boundTexturesStack.push(texture);
  12697. }
  12698. }
  12699. }
  12700. if (isTextureForRendering && this._activeChannel > -1) {
  12701. texture._designatedSlot = this._activeChannel;
  12702. if (!doNotBindUniformToTextureChannel) {
  12703. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12704. }
  12705. }
  12706. };
  12707. Engine.prototype._bindTexture = function (channel, texture) {
  12708. if (channel < 0) {
  12709. return;
  12710. }
  12711. if (texture) {
  12712. channel = this._getCorrectTextureChannel(channel, texture);
  12713. }
  12714. this._activateTextureChannel(channel);
  12715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12716. };
  12717. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12718. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12719. };
  12720. Engine.prototype.unbindAllTextures = function () {
  12721. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12722. this._activateTextureChannel(channel);
  12723. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12724. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12725. if (this.webGLVersion > 1) {
  12726. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12727. }
  12728. }
  12729. };
  12730. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12731. if (channel < 0) {
  12732. return;
  12733. }
  12734. if (uniform) {
  12735. this._boundUniforms[channel] = uniform;
  12736. }
  12737. this._setTexture(channel, texture);
  12738. };
  12739. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12740. if (!internalTexture) {
  12741. return -1;
  12742. }
  12743. internalTexture._initialSlot = channel;
  12744. if (this.disableTextureBindingOptimization) {
  12745. if (channel !== internalTexture._designatedSlot) {
  12746. this._textureCollisions.addCount(1, false);
  12747. }
  12748. }
  12749. else {
  12750. if (channel !== internalTexture._designatedSlot) {
  12751. if (internalTexture._designatedSlot > -1) {
  12752. return internalTexture._designatedSlot;
  12753. }
  12754. else {
  12755. // No slot for this texture, let's pick a new one (if we find a free slot)
  12756. if (this._nextFreeTextureSlots.length) {
  12757. return this._nextFreeTextureSlots[0];
  12758. }
  12759. // We need to recycle the oldest bound texture, sorry.
  12760. this._textureCollisions.addCount(1, false);
  12761. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12762. }
  12763. }
  12764. }
  12765. return channel;
  12766. };
  12767. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12768. var uniform = this._boundUniforms[sourceSlot];
  12769. this._gl.uniform1i(uniform, destination);
  12770. };
  12771. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12772. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12773. // Not ready?
  12774. if (!texture) {
  12775. if (this._boundTexturesCache[channel] != null) {
  12776. this._activateTextureChannel(channel);
  12777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12778. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12779. if (this.webGLVersion > 1) {
  12780. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12781. }
  12782. }
  12783. return false;
  12784. }
  12785. // Video
  12786. var alreadyActivated = false;
  12787. if (texture.video) {
  12788. this._activateTextureChannel(channel);
  12789. alreadyActivated = true;
  12790. texture.update();
  12791. }
  12792. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12793. texture.delayLoad();
  12794. return false;
  12795. }
  12796. var internalTexture;
  12797. if (texture.isReady()) {
  12798. internalTexture = texture.getInternalTexture();
  12799. }
  12800. else if (texture.isCube) {
  12801. internalTexture = this.emptyCubeTexture;
  12802. }
  12803. else if (texture.is3D) {
  12804. internalTexture = this.emptyTexture3D;
  12805. }
  12806. else {
  12807. internalTexture = this.emptyTexture;
  12808. }
  12809. if (!isPartOfTextureArray) {
  12810. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12811. }
  12812. if (this._boundTexturesCache[channel] === internalTexture) {
  12813. this._moveBoundTextureOnTop(internalTexture);
  12814. if (!isPartOfTextureArray) {
  12815. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12816. }
  12817. return false;
  12818. }
  12819. if (!alreadyActivated) {
  12820. this._activateTextureChannel(channel);
  12821. }
  12822. if (internalTexture && internalTexture.is3D) {
  12823. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12824. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12825. internalTexture._cachedWrapU = texture.wrapU;
  12826. switch (texture.wrapU) {
  12827. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12828. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12829. break;
  12830. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12831. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12832. break;
  12833. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12834. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12835. break;
  12836. }
  12837. }
  12838. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12839. internalTexture._cachedWrapV = texture.wrapV;
  12840. switch (texture.wrapV) {
  12841. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12843. break;
  12844. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12845. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12846. break;
  12847. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12848. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12849. break;
  12850. }
  12851. }
  12852. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12853. internalTexture._cachedWrapR = texture.wrapR;
  12854. switch (texture.wrapV) {
  12855. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12857. break;
  12858. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12859. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12860. break;
  12861. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12862. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12863. break;
  12864. }
  12865. }
  12866. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12867. }
  12868. else if (internalTexture && internalTexture.isCube) {
  12869. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12870. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12871. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12872. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12873. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12874. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12875. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12876. }
  12877. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12878. }
  12879. else {
  12880. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12881. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12882. internalTexture._cachedWrapU = texture.wrapU;
  12883. switch (texture.wrapU) {
  12884. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12885. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12886. break;
  12887. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12888. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12889. break;
  12890. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12892. break;
  12893. }
  12894. }
  12895. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12896. internalTexture._cachedWrapV = texture.wrapV;
  12897. switch (texture.wrapV) {
  12898. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12900. break;
  12901. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12903. break;
  12904. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12905. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12906. break;
  12907. }
  12908. }
  12909. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12910. }
  12911. return true;
  12912. };
  12913. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12914. if (channel < 0 || !uniform) {
  12915. return;
  12916. }
  12917. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12918. this._textureUnits = new Int32Array(textures.length);
  12919. }
  12920. for (var i = 0; i < textures.length; i++) {
  12921. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12922. }
  12923. this._gl.uniform1iv(uniform, this._textureUnits);
  12924. for (var index = 0; index < textures.length; index++) {
  12925. this._setTexture(this._textureUnits[index], textures[index], true);
  12926. }
  12927. };
  12928. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12929. var internalTexture = texture.getInternalTexture();
  12930. if (!internalTexture) {
  12931. return;
  12932. }
  12933. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12934. var value = texture.anisotropicFilteringLevel;
  12935. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12936. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12937. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12938. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12939. }
  12940. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12941. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12942. internalTexture._cachedAnisotropicFilteringLevel = value;
  12943. }
  12944. };
  12945. Engine.prototype.readPixels = function (x, y, width, height) {
  12946. var data = new Uint8Array(height * width * 4);
  12947. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12948. return data;
  12949. };
  12950. /**
  12951. * Add an externaly attached data from its key.
  12952. * This method call will fail and return false, if such key already exists.
  12953. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12954. * @param key the unique key that identifies the data
  12955. * @param data the data object to associate to the key for this Engine instance
  12956. * @return true if no such key were already present and the data was added successfully, false otherwise
  12957. */
  12958. Engine.prototype.addExternalData = function (key, data) {
  12959. if (!this._externalData) {
  12960. this._externalData = new BABYLON.StringDictionary();
  12961. }
  12962. return this._externalData.add(key, data);
  12963. };
  12964. /**
  12965. * Get an externaly attached data from its key
  12966. * @param key the unique key that identifies the data
  12967. * @return the associated data, if present (can be null), or undefined if not present
  12968. */
  12969. Engine.prototype.getExternalData = function (key) {
  12970. if (!this._externalData) {
  12971. this._externalData = new BABYLON.StringDictionary();
  12972. }
  12973. return this._externalData.get(key);
  12974. };
  12975. /**
  12976. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12977. * @param key the unique key that identifies the data
  12978. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12979. * @return the associated data, can be null if the factory returned null.
  12980. */
  12981. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12982. if (!this._externalData) {
  12983. this._externalData = new BABYLON.StringDictionary();
  12984. }
  12985. return this._externalData.getOrAddWithFactory(key, factory);
  12986. };
  12987. /**
  12988. * Remove an externaly attached data from the Engine instance
  12989. * @param key the unique key that identifies the data
  12990. * @return true if the data was successfully removed, false if it doesn't exist
  12991. */
  12992. Engine.prototype.removeExternalData = function (key) {
  12993. if (!this._externalData) {
  12994. this._externalData = new BABYLON.StringDictionary();
  12995. }
  12996. return this._externalData.remove(key);
  12997. };
  12998. Engine.prototype.unbindAllAttributes = function () {
  12999. if (this._mustWipeVertexAttributes) {
  13000. this._mustWipeVertexAttributes = false;
  13001. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13002. this._gl.disableVertexAttribArray(i);
  13003. this._vertexAttribArraysEnabled[i] = false;
  13004. this._currentBufferPointers[i].active = false;
  13005. }
  13006. return;
  13007. }
  13008. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13009. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13010. continue;
  13011. }
  13012. this._gl.disableVertexAttribArray(i);
  13013. this._vertexAttribArraysEnabled[i] = false;
  13014. this._currentBufferPointers[i].active = false;
  13015. }
  13016. };
  13017. Engine.prototype.releaseEffects = function () {
  13018. for (var name in this._compiledEffects) {
  13019. this._deleteProgram(this._compiledEffects[name]._program);
  13020. }
  13021. this._compiledEffects = {};
  13022. };
  13023. // Dispose
  13024. Engine.prototype.dispose = function () {
  13025. this.hideLoadingUI();
  13026. this.stopRenderLoop();
  13027. // Release postProcesses
  13028. while (this.postProcesses.length) {
  13029. this.postProcesses[0].dispose();
  13030. }
  13031. // Empty texture
  13032. if (this._emptyTexture) {
  13033. this._releaseTexture(this._emptyTexture);
  13034. this._emptyTexture = null;
  13035. }
  13036. if (this._emptyCubeTexture) {
  13037. this._releaseTexture(this._emptyCubeTexture);
  13038. this._emptyCubeTexture = null;
  13039. }
  13040. // Rescale PP
  13041. if (this._rescalePostProcess) {
  13042. this._rescalePostProcess.dispose();
  13043. }
  13044. // Release scenes
  13045. while (this.scenes.length) {
  13046. this.scenes[0].dispose();
  13047. }
  13048. // Release audio engine
  13049. if (Engine.audioEngine) {
  13050. Engine.audioEngine.dispose();
  13051. }
  13052. // Release effects
  13053. this.releaseEffects();
  13054. // Unbind
  13055. this.unbindAllAttributes();
  13056. if (this._dummyFramebuffer) {
  13057. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13058. }
  13059. //WebVR
  13060. this.disableVR();
  13061. // Events
  13062. if (BABYLON.Tools.IsWindowObjectExist()) {
  13063. window.removeEventListener("blur", this._onBlur);
  13064. window.removeEventListener("focus", this._onFocus);
  13065. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13066. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13067. if (this._renderingCanvas) {
  13068. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13069. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13070. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13071. if (!this._doNotHandleContextLost) {
  13072. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13073. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13074. }
  13075. }
  13076. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13077. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13078. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13079. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13080. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13081. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13082. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13083. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13084. if (this._onVrDisplayConnect) {
  13085. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13086. if (this._onVrDisplayDisconnect) {
  13087. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13088. }
  13089. if (this._onVrDisplayPresentChange) {
  13090. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13091. }
  13092. this._onVrDisplayConnect = null;
  13093. this._onVrDisplayDisconnect = null;
  13094. }
  13095. }
  13096. // Remove from Instances
  13097. var index = Engine.Instances.indexOf(this);
  13098. if (index >= 0) {
  13099. Engine.Instances.splice(index, 1);
  13100. }
  13101. this._workingCanvas = null;
  13102. this._workingContext = null;
  13103. this._currentBufferPointers = [];
  13104. this._renderingCanvas = null;
  13105. this._currentProgram = null;
  13106. this.onResizeObservable.clear();
  13107. this.onCanvasBlurObservable.clear();
  13108. this.onCanvasFocusObservable.clear();
  13109. this.onCanvasPointerOutObservable.clear();
  13110. this.onBeginFrameObservable.clear();
  13111. this.onEndFrameObservable.clear();
  13112. BABYLON.Effect.ResetCache();
  13113. // Abort active requests
  13114. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13115. var request = _a[_i];
  13116. request.abort();
  13117. }
  13118. };
  13119. // Loading screen
  13120. Engine.prototype.displayLoadingUI = function () {
  13121. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13122. return;
  13123. }
  13124. var loadingScreen = this.loadingScreen;
  13125. if (loadingScreen) {
  13126. loadingScreen.displayLoadingUI();
  13127. }
  13128. };
  13129. Engine.prototype.hideLoadingUI = function () {
  13130. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13131. return;
  13132. }
  13133. var loadingScreen = this.loadingScreen;
  13134. if (loadingScreen) {
  13135. loadingScreen.hideLoadingUI();
  13136. }
  13137. };
  13138. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13139. get: function () {
  13140. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13141. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13142. return this._loadingScreen;
  13143. },
  13144. set: function (loadingScreen) {
  13145. this._loadingScreen = loadingScreen;
  13146. },
  13147. enumerable: true,
  13148. configurable: true
  13149. });
  13150. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13151. set: function (text) {
  13152. this.loadingScreen.loadingUIText = text;
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13158. set: function (color) {
  13159. this.loadingScreen.loadingUIBackgroundColor = color;
  13160. },
  13161. enumerable: true,
  13162. configurable: true
  13163. });
  13164. Engine.prototype.attachContextLostEvent = function (callback) {
  13165. if (this._renderingCanvas) {
  13166. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13167. }
  13168. };
  13169. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13170. if (this._renderingCanvas) {
  13171. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13172. }
  13173. };
  13174. Engine.prototype.getVertexShaderSource = function (program) {
  13175. var shaders = this._gl.getAttachedShaders(program);
  13176. if (!shaders) {
  13177. return null;
  13178. }
  13179. return this._gl.getShaderSource(shaders[0]);
  13180. };
  13181. Engine.prototype.getFragmentShaderSource = function (program) {
  13182. var shaders = this._gl.getAttachedShaders(program);
  13183. if (!shaders) {
  13184. return null;
  13185. }
  13186. return this._gl.getShaderSource(shaders[1]);
  13187. };
  13188. Engine.prototype.getError = function () {
  13189. return this._gl.getError();
  13190. };
  13191. // FPS
  13192. Engine.prototype.getFps = function () {
  13193. return this._fps;
  13194. };
  13195. Engine.prototype.getDeltaTime = function () {
  13196. return this._deltaTime;
  13197. };
  13198. Engine.prototype._measureFps = function () {
  13199. this._performanceMonitor.sampleFrame();
  13200. this._fps = this._performanceMonitor.averageFPS;
  13201. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13202. };
  13203. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13204. if (faceIndex === void 0) { faceIndex = -1; }
  13205. var gl = this._gl;
  13206. if (!this._dummyFramebuffer) {
  13207. var dummy = gl.createFramebuffer();
  13208. if (!dummy) {
  13209. throw new Error("Unable to create dummy framebuffer");
  13210. }
  13211. this._dummyFramebuffer = dummy;
  13212. }
  13213. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13214. if (faceIndex > -1) {
  13215. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13216. }
  13217. else {
  13218. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13219. }
  13220. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13221. var buffer;
  13222. switch (readType) {
  13223. case gl.UNSIGNED_BYTE:
  13224. buffer = new Uint8Array(4 * width * height);
  13225. readType = gl.UNSIGNED_BYTE;
  13226. break;
  13227. default:
  13228. buffer = new Float32Array(4 * width * height);
  13229. readType = gl.FLOAT;
  13230. break;
  13231. }
  13232. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13233. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13234. return buffer;
  13235. };
  13236. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13237. if (this._webGLVersion > 1) {
  13238. return this._caps.colorBufferFloat;
  13239. }
  13240. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13241. };
  13242. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13243. if (this._webGLVersion > 1) {
  13244. return this._caps.colorBufferFloat;
  13245. }
  13246. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13247. };
  13248. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13249. Engine.prototype._canRenderToFramebuffer = function (type) {
  13250. var gl = this._gl;
  13251. //clear existing errors
  13252. while (gl.getError() !== gl.NO_ERROR) { }
  13253. var successful = true;
  13254. var texture = gl.createTexture();
  13255. gl.bindTexture(gl.TEXTURE_2D, texture);
  13256. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13259. var fb = gl.createFramebuffer();
  13260. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13261. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13262. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13263. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13264. successful = successful && (gl.getError() === gl.NO_ERROR);
  13265. //try render by clearing frame buffer's color buffer
  13266. if (successful) {
  13267. gl.clear(gl.COLOR_BUFFER_BIT);
  13268. successful = successful && (gl.getError() === gl.NO_ERROR);
  13269. }
  13270. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13271. if (successful) {
  13272. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13273. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13274. var readFormat = gl.RGBA;
  13275. var readType = gl.UNSIGNED_BYTE;
  13276. var buffer = new Uint8Array(4);
  13277. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13278. successful = successful && (gl.getError() === gl.NO_ERROR);
  13279. }
  13280. //clean up
  13281. gl.deleteTexture(texture);
  13282. gl.deleteFramebuffer(fb);
  13283. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13284. //clear accumulated errors
  13285. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13286. return successful;
  13287. };
  13288. Engine.prototype._getWebGLTextureType = function (type) {
  13289. if (type === Engine.TEXTURETYPE_FLOAT) {
  13290. return this._gl.FLOAT;
  13291. }
  13292. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13293. // Add Half Float Constant.
  13294. return this._gl.HALF_FLOAT_OES;
  13295. }
  13296. return this._gl.UNSIGNED_BYTE;
  13297. };
  13298. ;
  13299. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13300. if (this._webGLVersion === 1) {
  13301. return this._gl.RGBA;
  13302. }
  13303. if (type === Engine.TEXTURETYPE_FLOAT) {
  13304. return this._gl.RGBA32F;
  13305. }
  13306. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13307. return this._gl.RGBA16F;
  13308. }
  13309. return this._gl.RGBA;
  13310. };
  13311. ;
  13312. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13313. if (type === Engine.TEXTURETYPE_FLOAT) {
  13314. return this._gl.RGBA32F;
  13315. }
  13316. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13317. return this._gl.RGBA16F;
  13318. }
  13319. return this._gl.RGBA8;
  13320. };
  13321. ;
  13322. Engine.prototype.createQuery = function () {
  13323. return this._gl.createQuery();
  13324. };
  13325. Engine.prototype.deleteQuery = function (query) {
  13326. this._gl.deleteQuery(query);
  13327. return this;
  13328. };
  13329. Engine.prototype.isQueryResultAvailable = function (query) {
  13330. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13331. };
  13332. Engine.prototype.getQueryResult = function (query) {
  13333. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13334. };
  13335. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13336. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13337. this._gl.beginQuery(glAlgorithm, query);
  13338. return this;
  13339. };
  13340. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13341. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13342. this._gl.endQuery(glAlgorithm);
  13343. return this;
  13344. };
  13345. /* Time queries */
  13346. Engine.prototype._createTimeQuery = function () {
  13347. var timerQuery = this._caps.timerQuery;
  13348. if (timerQuery.createQueryEXT) {
  13349. return timerQuery.createQueryEXT();
  13350. }
  13351. return this.createQuery();
  13352. };
  13353. Engine.prototype._deleteTimeQuery = function (query) {
  13354. var timerQuery = this._caps.timerQuery;
  13355. if (timerQuery.deleteQueryEXT) {
  13356. timerQuery.deleteQueryEXT(query);
  13357. return;
  13358. }
  13359. this.deleteQuery(query);
  13360. };
  13361. Engine.prototype._getTimeQueryResult = function (query) {
  13362. var timerQuery = this._caps.timerQuery;
  13363. if (timerQuery.getQueryObjectEXT) {
  13364. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13365. }
  13366. return this.getQueryResult(query);
  13367. };
  13368. Engine.prototype._getTimeQueryAvailability = function (query) {
  13369. var timerQuery = this._caps.timerQuery;
  13370. if (timerQuery.getQueryObjectEXT) {
  13371. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13372. }
  13373. return this.isQueryResultAvailable(query);
  13374. };
  13375. Engine.prototype.startTimeQuery = function () {
  13376. var timerQuery = this._caps.timerQuery;
  13377. if (!timerQuery) {
  13378. return null;
  13379. }
  13380. var token = new BABYLON._TimeToken();
  13381. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13382. if (this._caps.canUseTimestampForTimerQuery) {
  13383. token._startTimeQuery = this._createTimeQuery();
  13384. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13385. }
  13386. else {
  13387. if (this._currentNonTimestampToken) {
  13388. return this._currentNonTimestampToken;
  13389. }
  13390. token._timeElapsedQuery = this._createTimeQuery();
  13391. if (timerQuery.beginQueryEXT) {
  13392. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13393. }
  13394. else {
  13395. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13396. }
  13397. this._currentNonTimestampToken = token;
  13398. }
  13399. return token;
  13400. };
  13401. Engine.prototype.endTimeQuery = function (token) {
  13402. var timerQuery = this._caps.timerQuery;
  13403. if (!timerQuery || !token) {
  13404. return -1;
  13405. }
  13406. if (this._caps.canUseTimestampForTimerQuery) {
  13407. if (!token._startTimeQuery) {
  13408. return -1;
  13409. }
  13410. if (!token._endTimeQuery) {
  13411. token._endTimeQuery = this._createTimeQuery();
  13412. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13413. }
  13414. }
  13415. else if (!token._timeElapsedQueryEnded) {
  13416. if (!token._timeElapsedQuery) {
  13417. return -1;
  13418. }
  13419. if (timerQuery.endQueryEXT) {
  13420. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13421. }
  13422. else {
  13423. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13424. }
  13425. token._timeElapsedQueryEnded = true;
  13426. }
  13427. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13428. var available = false;
  13429. if (token._endTimeQuery) {
  13430. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13431. }
  13432. else if (token._timeElapsedQuery) {
  13433. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13434. }
  13435. if (available && !disjoint) {
  13436. var result = 0;
  13437. if (this._caps.canUseTimestampForTimerQuery) {
  13438. if (!token._startTimeQuery || !token._endTimeQuery) {
  13439. return -1;
  13440. }
  13441. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13442. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13443. result = timeEnd - timeStart;
  13444. this._deleteTimeQuery(token._startTimeQuery);
  13445. this._deleteTimeQuery(token._endTimeQuery);
  13446. token._startTimeQuery = null;
  13447. token._endTimeQuery = null;
  13448. }
  13449. else {
  13450. if (!token._timeElapsedQuery) {
  13451. return -1;
  13452. }
  13453. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13454. this._deleteTimeQuery(token._timeElapsedQuery);
  13455. token._timeElapsedQuery = null;
  13456. token._timeElapsedQueryEnded = false;
  13457. this._currentNonTimestampToken = null;
  13458. }
  13459. return result;
  13460. }
  13461. return -1;
  13462. };
  13463. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13464. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13465. };
  13466. // Transform feedback
  13467. Engine.prototype.createTransformFeedback = function () {
  13468. return this._gl.createTransformFeedback();
  13469. };
  13470. Engine.prototype.deleteTransformFeedback = function (value) {
  13471. this._gl.deleteTransformFeedback(value);
  13472. };
  13473. Engine.prototype.bindTransformFeedback = function (value) {
  13474. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13475. };
  13476. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13477. if (usePoints === void 0) { usePoints = true; }
  13478. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13479. };
  13480. Engine.prototype.endTransformFeedback = function () {
  13481. this._gl.endTransformFeedback();
  13482. };
  13483. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13484. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13485. };
  13486. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13487. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13488. };
  13489. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13490. var _this = this;
  13491. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13492. this._activeRequests.push(request);
  13493. request.onCompleteObservable.add(function (request) {
  13494. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13495. });
  13496. return request;
  13497. };
  13498. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13499. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13500. var onload = function (data) {
  13501. loadedFiles[index] = data;
  13502. loadedFiles._internalCount++;
  13503. if (loadedFiles._internalCount === 6) {
  13504. onfinish(loadedFiles);
  13505. }
  13506. };
  13507. var onerror = function (request, exception) {
  13508. if (onErrorCallBack && request) {
  13509. onErrorCallBack(request.status + " " + request.statusText, exception);
  13510. }
  13511. };
  13512. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13513. };
  13514. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13515. if (onError === void 0) { onError = null; }
  13516. var loadedFiles = [];
  13517. loadedFiles._internalCount = 0;
  13518. for (var index = 0; index < 6; index++) {
  13519. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13520. }
  13521. };
  13522. // Statics
  13523. Engine.isSupported = function () {
  13524. try {
  13525. var tempcanvas = document.createElement("canvas");
  13526. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13527. return gl != null && !!window.WebGLRenderingContext;
  13528. }
  13529. catch (e) {
  13530. return false;
  13531. }
  13532. };
  13533. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13534. Engine.ExceptionList = [
  13535. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13536. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13537. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13538. ];
  13539. Engine.Instances = new Array();
  13540. // Const statics
  13541. Engine._ALPHA_DISABLE = 0;
  13542. Engine._ALPHA_ADD = 1;
  13543. Engine._ALPHA_COMBINE = 2;
  13544. Engine._ALPHA_SUBTRACT = 3;
  13545. Engine._ALPHA_MULTIPLY = 4;
  13546. Engine._ALPHA_MAXIMIZED = 5;
  13547. Engine._ALPHA_ONEONE = 6;
  13548. Engine._ALPHA_PREMULTIPLIED = 7;
  13549. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13550. Engine._ALPHA_INTERPOLATE = 9;
  13551. Engine._ALPHA_SCREENMODE = 10;
  13552. Engine._DELAYLOADSTATE_NONE = 0;
  13553. Engine._DELAYLOADSTATE_LOADED = 1;
  13554. Engine._DELAYLOADSTATE_LOADING = 2;
  13555. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13556. Engine._TEXTUREFORMAT_ALPHA = 0;
  13557. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13558. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13559. Engine._TEXTUREFORMAT_RGB = 4;
  13560. Engine._TEXTUREFORMAT_RGBA = 5;
  13561. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13562. Engine._TEXTURETYPE_FLOAT = 1;
  13563. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13564. // Depht or Stencil test Constants.
  13565. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13566. 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.
  13567. 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.
  13568. 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.
  13569. 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.
  13570. 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.
  13571. 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.
  13572. 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.
  13573. // Stencil Actions Constants.
  13574. Engine._KEEP = 0x1E00;
  13575. Engine._REPLACE = 0x1E01;
  13576. Engine._INCR = 0x1E02;
  13577. Engine._DECR = 0x1E03;
  13578. Engine._INVERT = 0x150A;
  13579. Engine._INCR_WRAP = 0x8507;
  13580. Engine._DECR_WRAP = 0x8508;
  13581. // Texture rescaling mode
  13582. Engine._SCALEMODE_FLOOR = 1;
  13583. Engine._SCALEMODE_NEAREST = 2;
  13584. Engine._SCALEMODE_CEILING = 3;
  13585. // Updatable statics so stick with vars here
  13586. Engine.CollisionsEpsilon = 0.001;
  13587. Engine.CodeRepository = "src/";
  13588. Engine.ShadersRepository = "src/Shaders/";
  13589. return Engine;
  13590. }());
  13591. BABYLON.Engine = Engine;
  13592. })(BABYLON || (BABYLON = {}));
  13593. //# sourceMappingURL=babylon.engine.js.map
  13594. var BABYLON;
  13595. (function (BABYLON) {
  13596. /**
  13597. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13598. */
  13599. var Node = /** @class */ (function () {
  13600. /**
  13601. * @constructor
  13602. * @param {string} name - the name and id to be given to this node
  13603. * @param {BABYLON.Scene} the scene this node will be added to
  13604. */
  13605. function Node(name, scene) {
  13606. if (scene === void 0) { scene = null; }
  13607. this.state = "";
  13608. this.metadata = null;
  13609. this.doNotSerialize = false;
  13610. this.animations = new Array();
  13611. this._ranges = {};
  13612. this._isEnabled = true;
  13613. this._isReady = true;
  13614. this._currentRenderId = -1;
  13615. this._parentRenderId = -1;
  13616. /**
  13617. * An event triggered when the mesh is disposed.
  13618. * @type {BABYLON.Observable}
  13619. */
  13620. this.onDisposeObservable = new BABYLON.Observable();
  13621. // Behaviors
  13622. this._behaviors = new Array();
  13623. this.name = name;
  13624. this.id = name;
  13625. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13626. this.uniqueId = this._scene.getUniqueId();
  13627. this._initCache();
  13628. }
  13629. Object.defineProperty(Node.prototype, "parent", {
  13630. get: function () {
  13631. return this._parentNode;
  13632. },
  13633. set: function (parent) {
  13634. if (this._parentNode === parent) {
  13635. return;
  13636. }
  13637. // Remove self from list of children of parent
  13638. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13639. var index = this._parentNode._children.indexOf(this);
  13640. if (index !== -1) {
  13641. this._parentNode._children.splice(index, 1);
  13642. }
  13643. }
  13644. // Store new parent
  13645. this._parentNode = parent;
  13646. // Add as child to new parent
  13647. if (this._parentNode) {
  13648. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13649. this._parentNode._children = new Array();
  13650. }
  13651. this._parentNode._children.push(this);
  13652. }
  13653. },
  13654. enumerable: true,
  13655. configurable: true
  13656. });
  13657. Node.prototype.getClassName = function () {
  13658. return "Node";
  13659. };
  13660. Object.defineProperty(Node.prototype, "onDispose", {
  13661. set: function (callback) {
  13662. if (this._onDisposeObserver) {
  13663. this.onDisposeObservable.remove(this._onDisposeObserver);
  13664. }
  13665. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13666. },
  13667. enumerable: true,
  13668. configurable: true
  13669. });
  13670. Node.prototype.getScene = function () {
  13671. return this._scene;
  13672. };
  13673. Node.prototype.getEngine = function () {
  13674. return this._scene.getEngine();
  13675. };
  13676. Node.prototype.addBehavior = function (behavior) {
  13677. var _this = this;
  13678. var index = this._behaviors.indexOf(behavior);
  13679. if (index !== -1) {
  13680. return this;
  13681. }
  13682. behavior.init();
  13683. if (this._scene.isLoading) {
  13684. // We defer the attach when the scene will be loaded
  13685. var observer = this._scene.onDataLoadedObservable.add(function () {
  13686. behavior.attach(_this);
  13687. setTimeout(function () {
  13688. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13689. _this._scene.onDataLoadedObservable.remove(observer);
  13690. }, 0);
  13691. });
  13692. }
  13693. else {
  13694. behavior.attach(this);
  13695. }
  13696. this._behaviors.push(behavior);
  13697. return this;
  13698. };
  13699. Node.prototype.removeBehavior = function (behavior) {
  13700. var index = this._behaviors.indexOf(behavior);
  13701. if (index === -1) {
  13702. return this;
  13703. }
  13704. this._behaviors[index].detach();
  13705. this._behaviors.splice(index, 1);
  13706. return this;
  13707. };
  13708. Object.defineProperty(Node.prototype, "behaviors", {
  13709. get: function () {
  13710. return this._behaviors;
  13711. },
  13712. enumerable: true,
  13713. configurable: true
  13714. });
  13715. Node.prototype.getBehaviorByName = function (name) {
  13716. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13717. var behavior = _a[_i];
  13718. if (behavior.name === name) {
  13719. return behavior;
  13720. }
  13721. }
  13722. return null;
  13723. };
  13724. // override it in derived class
  13725. Node.prototype.getWorldMatrix = function () {
  13726. return BABYLON.Matrix.Identity();
  13727. };
  13728. // override it in derived class if you add new variables to the cache
  13729. // and call the parent class method
  13730. Node.prototype._initCache = function () {
  13731. this._cache = {};
  13732. this._cache.parent = undefined;
  13733. };
  13734. Node.prototype.updateCache = function (force) {
  13735. if (!force && this.isSynchronized())
  13736. return;
  13737. this._cache.parent = this.parent;
  13738. this._updateCache();
  13739. };
  13740. // override it in derived class if you add new variables to the cache
  13741. // and call the parent class method if !ignoreParentClass
  13742. Node.prototype._updateCache = function (ignoreParentClass) {
  13743. };
  13744. // override it in derived class if you add new variables to the cache
  13745. Node.prototype._isSynchronized = function () {
  13746. return true;
  13747. };
  13748. Node.prototype._markSyncedWithParent = function () {
  13749. if (this.parent) {
  13750. this._parentRenderId = this.parent._currentRenderId;
  13751. }
  13752. };
  13753. Node.prototype.isSynchronizedWithParent = function () {
  13754. if (!this.parent) {
  13755. return true;
  13756. }
  13757. if (this._parentRenderId !== this.parent._currentRenderId) {
  13758. return false;
  13759. }
  13760. return this.parent.isSynchronized();
  13761. };
  13762. Node.prototype.isSynchronized = function (updateCache) {
  13763. var check = this.hasNewParent();
  13764. check = check || !this.isSynchronizedWithParent();
  13765. check = check || !this._isSynchronized();
  13766. if (updateCache)
  13767. this.updateCache(true);
  13768. return !check;
  13769. };
  13770. Node.prototype.hasNewParent = function (update) {
  13771. if (this._cache.parent === this.parent)
  13772. return false;
  13773. if (update)
  13774. this._cache.parent = this.parent;
  13775. return true;
  13776. };
  13777. /**
  13778. * Is this node ready to be used/rendered
  13779. * @return {boolean} is it ready
  13780. */
  13781. Node.prototype.isReady = function () {
  13782. return this._isReady;
  13783. };
  13784. /**
  13785. * Is this node enabled.
  13786. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  13787. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13788. * @return {boolean} whether this node (and its parent) is enabled.
  13789. * @see setEnabled
  13790. */
  13791. Node.prototype.isEnabled = function (checkAncestors) {
  13792. if (checkAncestors === void 0) { checkAncestors = true; }
  13793. if (checkAncestors === false) {
  13794. return this._isEnabled;
  13795. }
  13796. if (this._isEnabled === false) {
  13797. return false;
  13798. }
  13799. if (this.parent !== undefined && this.parent !== null) {
  13800. return this.parent.isEnabled(checkAncestors);
  13801. }
  13802. return true;
  13803. };
  13804. /**
  13805. * Set the enabled state of this node.
  13806. * @param {boolean} value - the new enabled state
  13807. * @see isEnabled
  13808. */
  13809. Node.prototype.setEnabled = function (value) {
  13810. this._isEnabled = value;
  13811. };
  13812. /**
  13813. * Is this node a descendant of the given node.
  13814. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13815. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13816. * @see parent
  13817. */
  13818. Node.prototype.isDescendantOf = function (ancestor) {
  13819. if (this.parent) {
  13820. if (this.parent === ancestor) {
  13821. return true;
  13822. }
  13823. return this.parent.isDescendantOf(ancestor);
  13824. }
  13825. return false;
  13826. };
  13827. /**
  13828. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13829. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13830. * @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.
  13831. * @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.
  13832. */
  13833. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13834. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13835. if (!this._children) {
  13836. return;
  13837. }
  13838. for (var index = 0; index < this._children.length; index++) {
  13839. var item = this._children[index];
  13840. if (!predicate || predicate(item)) {
  13841. results.push(item);
  13842. }
  13843. if (!directDescendantsOnly) {
  13844. item._getDescendants(results, false, predicate);
  13845. }
  13846. }
  13847. };
  13848. /**
  13849. * Will return all nodes that have this node as ascendant.
  13850. * @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.
  13851. * @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.
  13852. * @return {BABYLON.Node[]} all children nodes of all types.
  13853. */
  13854. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13855. var results = new Array();
  13856. this._getDescendants(results, directDescendantsOnly, predicate);
  13857. return results;
  13858. };
  13859. /**
  13860. * Get all child-meshes of this node.
  13861. */
  13862. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13863. var results = [];
  13864. this._getDescendants(results, directDescendantsOnly, function (node) {
  13865. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13866. });
  13867. return results;
  13868. };
  13869. /**
  13870. * Get all child-transformNodes of this node.
  13871. */
  13872. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13873. var results = [];
  13874. this._getDescendants(results, directDescendantsOnly, function (node) {
  13875. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13876. });
  13877. return results;
  13878. };
  13879. /**
  13880. * Get all direct children of this node.
  13881. */
  13882. Node.prototype.getChildren = function (predicate) {
  13883. return this.getDescendants(true, predicate);
  13884. };
  13885. Node.prototype._setReady = function (state) {
  13886. if (state === this._isReady) {
  13887. return;
  13888. }
  13889. if (!state) {
  13890. this._isReady = false;
  13891. return;
  13892. }
  13893. this._isReady = true;
  13894. if (this.onReady) {
  13895. this.onReady(this);
  13896. }
  13897. };
  13898. Node.prototype.getAnimationByName = function (name) {
  13899. for (var i = 0; i < this.animations.length; i++) {
  13900. var animation = this.animations[i];
  13901. if (animation.name === name) {
  13902. return animation;
  13903. }
  13904. }
  13905. return null;
  13906. };
  13907. Node.prototype.createAnimationRange = function (name, from, to) {
  13908. // check name not already in use
  13909. if (!this._ranges[name]) {
  13910. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13911. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13912. if (this.animations[i]) {
  13913. this.animations[i].createRange(name, from, to);
  13914. }
  13915. }
  13916. }
  13917. };
  13918. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13919. if (deleteFrames === void 0) { deleteFrames = true; }
  13920. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13921. if (this.animations[i]) {
  13922. this.animations[i].deleteRange(name, deleteFrames);
  13923. }
  13924. }
  13925. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13926. };
  13927. Node.prototype.getAnimationRange = function (name) {
  13928. return this._ranges[name];
  13929. };
  13930. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13931. var range = this.getAnimationRange(name);
  13932. if (!range) {
  13933. return;
  13934. }
  13935. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13936. };
  13937. Node.prototype.serializeAnimationRanges = function () {
  13938. var serializationRanges = [];
  13939. for (var name in this._ranges) {
  13940. var localRange = this._ranges[name];
  13941. if (!localRange) {
  13942. continue;
  13943. }
  13944. var range = {};
  13945. range.name = name;
  13946. range.from = localRange.from;
  13947. range.to = localRange.to;
  13948. serializationRanges.push(range);
  13949. }
  13950. return serializationRanges;
  13951. };
  13952. // override it in derived class
  13953. Node.prototype.computeWorldMatrix = function (force) {
  13954. return BABYLON.Matrix.Identity();
  13955. };
  13956. Node.prototype.dispose = function () {
  13957. this.parent = null;
  13958. // Callback
  13959. this.onDisposeObservable.notifyObservers(this);
  13960. this.onDisposeObservable.clear();
  13961. // Behaviors
  13962. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13963. var behavior = _a[_i];
  13964. behavior.detach();
  13965. }
  13966. this._behaviors = [];
  13967. };
  13968. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13969. if (parsedNode.ranges) {
  13970. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13971. var data = parsedNode.ranges[index];
  13972. node.createAnimationRange(data.name, data.from, data.to);
  13973. }
  13974. }
  13975. };
  13976. __decorate([
  13977. BABYLON.serialize()
  13978. ], Node.prototype, "name", void 0);
  13979. __decorate([
  13980. BABYLON.serialize()
  13981. ], Node.prototype, "id", void 0);
  13982. __decorate([
  13983. BABYLON.serialize()
  13984. ], Node.prototype, "uniqueId", void 0);
  13985. __decorate([
  13986. BABYLON.serialize()
  13987. ], Node.prototype, "state", void 0);
  13988. __decorate([
  13989. BABYLON.serialize()
  13990. ], Node.prototype, "metadata", void 0);
  13991. return Node;
  13992. }());
  13993. BABYLON.Node = Node;
  13994. })(BABYLON || (BABYLON = {}));
  13995. //# sourceMappingURL=babylon.node.js.map
  13996. var BABYLON;
  13997. (function (BABYLON) {
  13998. var BoundingSphere = /** @class */ (function () {
  13999. function BoundingSphere(minimum, maximum) {
  14000. this.minimum = minimum;
  14001. this.maximum = maximum;
  14002. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14003. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14004. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14005. this.radius = distance * 0.5;
  14006. this.centerWorld = BABYLON.Vector3.Zero();
  14007. this._update(BABYLON.Matrix.Identity());
  14008. }
  14009. // Methods
  14010. BoundingSphere.prototype._update = function (world) {
  14011. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14012. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14013. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14014. };
  14015. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14016. for (var i = 0; i < 6; i++) {
  14017. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14018. return false;
  14019. }
  14020. return true;
  14021. };
  14022. BoundingSphere.prototype.intersectsPoint = function (point) {
  14023. var x = this.centerWorld.x - point.x;
  14024. var y = this.centerWorld.y - point.y;
  14025. var z = this.centerWorld.z - point.z;
  14026. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14027. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14028. return false;
  14029. return true;
  14030. };
  14031. // Statics
  14032. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14033. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14034. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14035. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14036. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14037. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14038. return false;
  14039. return true;
  14040. };
  14041. return BoundingSphere;
  14042. }());
  14043. BABYLON.BoundingSphere = BoundingSphere;
  14044. })(BABYLON || (BABYLON = {}));
  14045. //# sourceMappingURL=babylon.boundingSphere.js.map
  14046. var BABYLON;
  14047. (function (BABYLON) {
  14048. var BoundingBox = /** @class */ (function () {
  14049. function BoundingBox(minimum, maximum) {
  14050. this.minimum = minimum;
  14051. this.maximum = maximum;
  14052. this.vectors = new Array();
  14053. this.vectorsWorld = new Array();
  14054. // Bounding vectors
  14055. this.vectors.push(this.minimum.clone());
  14056. this.vectors.push(this.maximum.clone());
  14057. this.vectors.push(this.minimum.clone());
  14058. this.vectors[2].x = this.maximum.x;
  14059. this.vectors.push(this.minimum.clone());
  14060. this.vectors[3].y = this.maximum.y;
  14061. this.vectors.push(this.minimum.clone());
  14062. this.vectors[4].z = this.maximum.z;
  14063. this.vectors.push(this.maximum.clone());
  14064. this.vectors[5].z = this.minimum.z;
  14065. this.vectors.push(this.maximum.clone());
  14066. this.vectors[6].x = this.minimum.x;
  14067. this.vectors.push(this.maximum.clone());
  14068. this.vectors[7].y = this.minimum.y;
  14069. // OBB
  14070. this.center = this.maximum.add(this.minimum).scale(0.5);
  14071. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14072. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14073. // World
  14074. for (var index = 0; index < this.vectors.length; index++) {
  14075. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14076. }
  14077. this.minimumWorld = BABYLON.Vector3.Zero();
  14078. this.maximumWorld = BABYLON.Vector3.Zero();
  14079. this.centerWorld = BABYLON.Vector3.Zero();
  14080. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14081. this._update(BABYLON.Matrix.Identity());
  14082. }
  14083. // Methods
  14084. BoundingBox.prototype.getWorldMatrix = function () {
  14085. return this._worldMatrix;
  14086. };
  14087. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14088. this._worldMatrix.copyFrom(matrix);
  14089. return this;
  14090. };
  14091. BoundingBox.prototype._update = function (world) {
  14092. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14093. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14094. for (var index = 0; index < this.vectors.length; index++) {
  14095. var v = this.vectorsWorld[index];
  14096. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14097. if (v.x < this.minimumWorld.x)
  14098. this.minimumWorld.x = v.x;
  14099. if (v.y < this.minimumWorld.y)
  14100. this.minimumWorld.y = v.y;
  14101. if (v.z < this.minimumWorld.z)
  14102. this.minimumWorld.z = v.z;
  14103. if (v.x > this.maximumWorld.x)
  14104. this.maximumWorld.x = v.x;
  14105. if (v.y > this.maximumWorld.y)
  14106. this.maximumWorld.y = v.y;
  14107. if (v.z > this.maximumWorld.z)
  14108. this.maximumWorld.z = v.z;
  14109. }
  14110. // Extend
  14111. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14112. this.extendSizeWorld.scaleInPlace(0.5);
  14113. // OBB
  14114. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14115. this.centerWorld.scaleInPlace(0.5);
  14116. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14117. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14118. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14119. this._worldMatrix = world;
  14120. };
  14121. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14122. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14123. };
  14124. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14125. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14126. };
  14127. BoundingBox.prototype.intersectsPoint = function (point) {
  14128. var delta = -BABYLON.Epsilon;
  14129. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14130. return false;
  14131. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14132. return false;
  14133. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14134. return false;
  14135. return true;
  14136. };
  14137. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14138. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14139. };
  14140. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14141. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14142. return false;
  14143. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14144. return false;
  14145. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14146. return false;
  14147. return true;
  14148. };
  14149. // Statics
  14150. BoundingBox.Intersects = function (box0, box1) {
  14151. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14152. return false;
  14153. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14154. return false;
  14155. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14156. return false;
  14157. return true;
  14158. };
  14159. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14160. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14161. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14162. return (num <= (sphereRadius * sphereRadius));
  14163. };
  14164. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14165. for (var p = 0; p < 6; p++) {
  14166. for (var i = 0; i < 8; i++) {
  14167. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14168. return false;
  14169. }
  14170. }
  14171. }
  14172. return true;
  14173. };
  14174. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14175. for (var p = 0; p < 6; p++) {
  14176. var inCount = 8;
  14177. for (var i = 0; i < 8; i++) {
  14178. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14179. --inCount;
  14180. }
  14181. else {
  14182. break;
  14183. }
  14184. }
  14185. if (inCount === 0)
  14186. return false;
  14187. }
  14188. return true;
  14189. };
  14190. return BoundingBox;
  14191. }());
  14192. BABYLON.BoundingBox = BoundingBox;
  14193. })(BABYLON || (BABYLON = {}));
  14194. //# sourceMappingURL=babylon.boundingBox.js.map
  14195. var BABYLON;
  14196. (function (BABYLON) {
  14197. var computeBoxExtents = function (axis, box) {
  14198. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14199. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14200. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14201. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14202. var r = r0 + r1 + r2;
  14203. return {
  14204. min: p - r,
  14205. max: p + r
  14206. };
  14207. };
  14208. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14209. var axisOverlap = function (axis, box0, box1) {
  14210. var result0 = computeBoxExtents(axis, box0);
  14211. var result1 = computeBoxExtents(axis, box1);
  14212. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14213. };
  14214. var BoundingInfo = /** @class */ (function () {
  14215. function BoundingInfo(minimum, maximum) {
  14216. this.minimum = minimum;
  14217. this.maximum = maximum;
  14218. this._isLocked = false;
  14219. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14220. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14221. }
  14222. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14223. get: function () {
  14224. return this._isLocked;
  14225. },
  14226. set: function (value) {
  14227. this._isLocked = value;
  14228. },
  14229. enumerable: true,
  14230. configurable: true
  14231. });
  14232. // Methods
  14233. BoundingInfo.prototype.update = function (world) {
  14234. if (this._isLocked) {
  14235. return;
  14236. }
  14237. this.boundingBox._update(world);
  14238. this.boundingSphere._update(world);
  14239. };
  14240. /**
  14241. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14242. * @param center New center of the bounding info
  14243. * @param extend New extend of the bounding info
  14244. */
  14245. BoundingInfo.prototype.centerOn = function (center, extend) {
  14246. this.minimum = center.subtract(extend);
  14247. this.maximum = center.add(extend);
  14248. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14249. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14250. return this;
  14251. };
  14252. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14253. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14254. return false;
  14255. return this.boundingBox.isInFrustum(frustumPlanes);
  14256. };
  14257. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14258. /**
  14259. * Gets the world distance between the min and max points of the bounding box
  14260. */
  14261. get: function () {
  14262. var boundingBox = this.boundingBox;
  14263. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14264. return size.length();
  14265. },
  14266. enumerable: true,
  14267. configurable: true
  14268. });
  14269. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14270. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14271. };
  14272. BoundingInfo.prototype._checkCollision = function (collider) {
  14273. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14274. };
  14275. BoundingInfo.prototype.intersectsPoint = function (point) {
  14276. if (!this.boundingSphere.centerWorld) {
  14277. return false;
  14278. }
  14279. if (!this.boundingSphere.intersectsPoint(point)) {
  14280. return false;
  14281. }
  14282. if (!this.boundingBox.intersectsPoint(point)) {
  14283. return false;
  14284. }
  14285. return true;
  14286. };
  14287. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14288. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14289. return false;
  14290. }
  14291. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14292. return false;
  14293. }
  14294. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14295. return false;
  14296. }
  14297. if (!precise) {
  14298. return true;
  14299. }
  14300. var box0 = this.boundingBox;
  14301. var box1 = boundingInfo.boundingBox;
  14302. if (!axisOverlap(box0.directions[0], box0, box1))
  14303. return false;
  14304. if (!axisOverlap(box0.directions[1], box0, box1))
  14305. return false;
  14306. if (!axisOverlap(box0.directions[2], box0, box1))
  14307. return false;
  14308. if (!axisOverlap(box1.directions[0], box0, box1))
  14309. return false;
  14310. if (!axisOverlap(box1.directions[1], box0, box1))
  14311. return false;
  14312. if (!axisOverlap(box1.directions[2], box0, box1))
  14313. return false;
  14314. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14315. return false;
  14316. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14317. return false;
  14318. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14319. return false;
  14320. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14321. return false;
  14322. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14323. return false;
  14324. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14325. return false;
  14326. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14327. return false;
  14328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14329. return false;
  14330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14331. return false;
  14332. return true;
  14333. };
  14334. return BoundingInfo;
  14335. }());
  14336. BABYLON.BoundingInfo = BoundingInfo;
  14337. })(BABYLON || (BABYLON = {}));
  14338. //# sourceMappingURL=babylon.boundingInfo.js.map
  14339. var BABYLON;
  14340. (function (BABYLON) {
  14341. var TransformNode = /** @class */ (function (_super) {
  14342. __extends(TransformNode, _super);
  14343. function TransformNode(name, scene, isPure) {
  14344. if (scene === void 0) { scene = null; }
  14345. if (isPure === void 0) { isPure = true; }
  14346. var _this = _super.call(this, name, scene) || this;
  14347. // Properties
  14348. _this._rotation = BABYLON.Vector3.Zero();
  14349. _this._scaling = BABYLON.Vector3.One();
  14350. _this._isDirty = false;
  14351. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14352. _this.scalingDeterminant = 1;
  14353. _this.infiniteDistance = false;
  14354. _this.position = BABYLON.Vector3.Zero();
  14355. _this._localWorld = BABYLON.Matrix.Zero();
  14356. _this._worldMatrix = BABYLON.Matrix.Zero();
  14357. _this._worldMatrixDeterminant = 0;
  14358. _this._absolutePosition = BABYLON.Vector3.Zero();
  14359. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14360. _this._postMultiplyPivotMatrix = false;
  14361. _this._isWorldMatrixFrozen = false;
  14362. /**
  14363. * An event triggered after the world matrix is updated
  14364. * @type {BABYLON.Observable}
  14365. */
  14366. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14367. _this._nonUniformScaling = false;
  14368. if (isPure) {
  14369. _this.getScene().addTransformNode(_this);
  14370. }
  14371. return _this;
  14372. }
  14373. Object.defineProperty(TransformNode.prototype, "rotation", {
  14374. /**
  14375. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14376. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14377. * Default : (0.0, 0.0, 0.0)
  14378. */
  14379. get: function () {
  14380. return this._rotation;
  14381. },
  14382. set: function (newRotation) {
  14383. this._rotation = newRotation;
  14384. },
  14385. enumerable: true,
  14386. configurable: true
  14387. });
  14388. Object.defineProperty(TransformNode.prototype, "scaling", {
  14389. /**
  14390. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14391. * Default : (1.0, 1.0, 1.0)
  14392. */
  14393. get: function () {
  14394. return this._scaling;
  14395. },
  14396. /**
  14397. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14398. * Default : (1.0, 1.0, 1.0)
  14399. */
  14400. set: function (newScaling) {
  14401. this._scaling = newScaling;
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14407. /**
  14408. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14409. * It's null by default.
  14410. * 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)
  14411. */
  14412. get: function () {
  14413. return this._rotationQuaternion;
  14414. },
  14415. set: function (quaternion) {
  14416. this._rotationQuaternion = quaternion;
  14417. //reset the rotation vector.
  14418. if (quaternion && this.rotation.length()) {
  14419. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14420. }
  14421. },
  14422. enumerable: true,
  14423. configurable: true
  14424. });
  14425. /**
  14426. * Returns the latest update of the World matrix
  14427. * Returns a Matrix.
  14428. */
  14429. TransformNode.prototype.getWorldMatrix = function () {
  14430. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14431. this.computeWorldMatrix();
  14432. }
  14433. return this._worldMatrix;
  14434. };
  14435. /**
  14436. * Returns the latest update of the World matrix determinant.
  14437. */
  14438. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14439. return this._worldMatrixDeterminant;
  14440. };
  14441. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14442. /**
  14443. * Returns directly the latest state of the mesh World matrix.
  14444. * A Matrix is returned.
  14445. */
  14446. get: function () {
  14447. return this._worldMatrix;
  14448. },
  14449. enumerable: true,
  14450. configurable: true
  14451. });
  14452. /**
  14453. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14454. * Returns the AbstractMesh.
  14455. */
  14456. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14457. this._poseMatrix.copyFrom(matrix);
  14458. return this;
  14459. };
  14460. /**
  14461. * Returns the mesh Pose matrix.
  14462. * Returned object : Matrix
  14463. */
  14464. TransformNode.prototype.getPoseMatrix = function () {
  14465. return this._poseMatrix;
  14466. };
  14467. TransformNode.prototype._isSynchronized = function () {
  14468. if (this._isDirty) {
  14469. return false;
  14470. }
  14471. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14472. return false;
  14473. if (this._cache.pivotMatrixUpdated) {
  14474. return false;
  14475. }
  14476. if (this.infiniteDistance) {
  14477. return false;
  14478. }
  14479. if (!this._cache.position.equals(this.position))
  14480. return false;
  14481. if (this.rotationQuaternion) {
  14482. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14483. return false;
  14484. }
  14485. if (!this._cache.rotation.equals(this.rotation))
  14486. return false;
  14487. if (!this._cache.scaling.equals(this.scaling))
  14488. return false;
  14489. return true;
  14490. };
  14491. TransformNode.prototype._initCache = function () {
  14492. _super.prototype._initCache.call(this);
  14493. this._cache.localMatrixUpdated = false;
  14494. this._cache.position = BABYLON.Vector3.Zero();
  14495. this._cache.scaling = BABYLON.Vector3.Zero();
  14496. this._cache.rotation = BABYLON.Vector3.Zero();
  14497. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14498. this._cache.billboardMode = -1;
  14499. };
  14500. TransformNode.prototype.markAsDirty = function (property) {
  14501. if (property === "rotation") {
  14502. this.rotationQuaternion = null;
  14503. }
  14504. this._currentRenderId = Number.MAX_VALUE;
  14505. this._isDirty = true;
  14506. return this;
  14507. };
  14508. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14509. /**
  14510. * Returns the current mesh absolute position.
  14511. * Retuns a Vector3.
  14512. */
  14513. get: function () {
  14514. return this._absolutePosition;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. /**
  14520. * Sets a new pivot matrix to the mesh.
  14521. * Returns the AbstractMesh.
  14522. */
  14523. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14524. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14525. this._pivotMatrix = matrix.clone();
  14526. this._cache.pivotMatrixUpdated = true;
  14527. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14528. if (this._postMultiplyPivotMatrix) {
  14529. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14530. }
  14531. return this;
  14532. };
  14533. /**
  14534. * Returns the mesh pivot matrix.
  14535. * Default : Identity.
  14536. * A Matrix is returned.
  14537. */
  14538. TransformNode.prototype.getPivotMatrix = function () {
  14539. return this._pivotMatrix;
  14540. };
  14541. /**
  14542. * Prevents the World matrix to be computed any longer.
  14543. * Returns the AbstractMesh.
  14544. */
  14545. TransformNode.prototype.freezeWorldMatrix = function () {
  14546. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14547. this.computeWorldMatrix(true);
  14548. this._isWorldMatrixFrozen = true;
  14549. return this;
  14550. };
  14551. /**
  14552. * Allows back the World matrix computation.
  14553. * Returns the AbstractMesh.
  14554. */
  14555. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14556. this._isWorldMatrixFrozen = false;
  14557. this.computeWorldMatrix(true);
  14558. return this;
  14559. };
  14560. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14561. /**
  14562. * True if the World matrix has been frozen.
  14563. * Returns a boolean.
  14564. */
  14565. get: function () {
  14566. return this._isWorldMatrixFrozen;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. /**
  14572. * Retuns the mesh absolute position in the World.
  14573. * Returns a Vector3.
  14574. */
  14575. TransformNode.prototype.getAbsolutePosition = function () {
  14576. this.computeWorldMatrix();
  14577. return this._absolutePosition;
  14578. };
  14579. /**
  14580. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14581. * Returns the AbstractMesh.
  14582. */
  14583. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14584. if (!absolutePosition) {
  14585. return this;
  14586. }
  14587. var absolutePositionX;
  14588. var absolutePositionY;
  14589. var absolutePositionZ;
  14590. if (absolutePosition.x === undefined) {
  14591. if (arguments.length < 3) {
  14592. return this;
  14593. }
  14594. absolutePositionX = arguments[0];
  14595. absolutePositionY = arguments[1];
  14596. absolutePositionZ = arguments[2];
  14597. }
  14598. else {
  14599. absolutePositionX = absolutePosition.x;
  14600. absolutePositionY = absolutePosition.y;
  14601. absolutePositionZ = absolutePosition.z;
  14602. }
  14603. if (this.parent) {
  14604. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14605. invertParentWorldMatrix.invert();
  14606. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14607. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14608. }
  14609. else {
  14610. this.position.x = absolutePositionX;
  14611. this.position.y = absolutePositionY;
  14612. this.position.z = absolutePositionZ;
  14613. }
  14614. return this;
  14615. };
  14616. /**
  14617. * Sets the mesh position in its local space.
  14618. * Returns the AbstractMesh.
  14619. */
  14620. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14621. this.computeWorldMatrix();
  14622. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14623. return this;
  14624. };
  14625. /**
  14626. * Returns the mesh position in the local space from the current World matrix values.
  14627. * Returns a new Vector3.
  14628. */
  14629. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14630. this.computeWorldMatrix();
  14631. var invLocalWorldMatrix = this._localWorld.clone();
  14632. invLocalWorldMatrix.invert();
  14633. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14634. };
  14635. /**
  14636. * Translates the mesh along the passed Vector3 in its local space.
  14637. * Returns the AbstractMesh.
  14638. */
  14639. TransformNode.prototype.locallyTranslate = function (vector3) {
  14640. this.computeWorldMatrix(true);
  14641. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14642. return this;
  14643. };
  14644. /**
  14645. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14646. * @param targetPoint the position (must be in same space as current mesh) to look at
  14647. * @param yawCor optional yaw (y-axis) correction in radians
  14648. * @param pitchCor optional pitch (x-axis) correction in radians
  14649. * @param rollCor optional roll (z-axis) correction in radians
  14650. * @param space the choosen space of the target
  14651. * @returns the TransformNode.
  14652. */
  14653. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14654. if (yawCor === void 0) { yawCor = 0; }
  14655. if (pitchCor === void 0) { pitchCor = 0; }
  14656. if (rollCor === void 0) { rollCor = 0; }
  14657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14658. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14659. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14660. targetPoint.subtractToRef(pos, dv);
  14661. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14662. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14663. var pitch = Math.atan2(dv.y, len);
  14664. if (this.rotationQuaternion) {
  14665. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14666. }
  14667. else {
  14668. this.rotation.x = pitch + pitchCor;
  14669. this.rotation.y = yaw + yawCor;
  14670. this.rotation.z = rollCor;
  14671. }
  14672. return this;
  14673. };
  14674. /**
  14675. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14676. * This Vector3 is expressed in the World space.
  14677. */
  14678. TransformNode.prototype.getDirection = function (localAxis) {
  14679. var result = BABYLON.Vector3.Zero();
  14680. this.getDirectionToRef(localAxis, result);
  14681. return result;
  14682. };
  14683. /**
  14684. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14685. * localAxis is expressed in the mesh local space.
  14686. * result is computed in the Wordl space from the mesh World matrix.
  14687. * Returns the AbstractMesh.
  14688. */
  14689. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14690. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14691. return this;
  14692. };
  14693. TransformNode.prototype.setPivotPoint = function (point, space) {
  14694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14695. if (this.getScene().getRenderId() == 0) {
  14696. this.computeWorldMatrix(true);
  14697. }
  14698. var wm = this.getWorldMatrix();
  14699. if (space == BABYLON.Space.WORLD) {
  14700. var tmat = BABYLON.Tmp.Matrix[0];
  14701. wm.invertToRef(tmat);
  14702. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14703. }
  14704. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14705. this._pivotMatrix.m[12] = -point.x;
  14706. this._pivotMatrix.m[13] = -point.y;
  14707. this._pivotMatrix.m[14] = -point.z;
  14708. this._cache.pivotMatrixUpdated = true;
  14709. return this;
  14710. };
  14711. /**
  14712. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14713. */
  14714. TransformNode.prototype.getPivotPoint = function () {
  14715. var point = BABYLON.Vector3.Zero();
  14716. this.getPivotPointToRef(point);
  14717. return point;
  14718. };
  14719. /**
  14720. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14721. * Returns the AbstractMesh.
  14722. */
  14723. TransformNode.prototype.getPivotPointToRef = function (result) {
  14724. result.x = -this._pivotMatrix.m[12];
  14725. result.y = -this._pivotMatrix.m[13];
  14726. result.z = -this._pivotMatrix.m[14];
  14727. return this;
  14728. };
  14729. /**
  14730. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14731. */
  14732. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14733. var point = BABYLON.Vector3.Zero();
  14734. this.getAbsolutePivotPointToRef(point);
  14735. return point;
  14736. };
  14737. /**
  14738. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14739. * Returns the AbstractMesh.
  14740. */
  14741. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14742. result.x = this._pivotMatrix.m[12];
  14743. result.y = this._pivotMatrix.m[13];
  14744. result.z = this._pivotMatrix.m[14];
  14745. this.getPivotPointToRef(result);
  14746. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14747. return this;
  14748. };
  14749. /**
  14750. * Defines the passed node as the parent of the current node.
  14751. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14752. * Returns the TransformNode.
  14753. */
  14754. TransformNode.prototype.setParent = function (node) {
  14755. if (node === null) {
  14756. var rotation = BABYLON.Tmp.Quaternion[0];
  14757. var position = BABYLON.Tmp.Vector3[0];
  14758. var scale = BABYLON.Tmp.Vector3[1];
  14759. if (this.parent && this.parent.computeWorldMatrix) {
  14760. this.parent.computeWorldMatrix(true);
  14761. }
  14762. this.computeWorldMatrix(true);
  14763. this.getWorldMatrix().decompose(scale, rotation, position);
  14764. if (this.rotationQuaternion) {
  14765. this.rotationQuaternion.copyFrom(rotation);
  14766. }
  14767. else {
  14768. rotation.toEulerAnglesToRef(this.rotation);
  14769. }
  14770. this.scaling.x = scale.x;
  14771. this.scaling.y = scale.y;
  14772. this.scaling.z = scale.z;
  14773. this.position.x = position.x;
  14774. this.position.y = position.y;
  14775. this.position.z = position.z;
  14776. }
  14777. else {
  14778. var rotation = BABYLON.Tmp.Quaternion[0];
  14779. var position = BABYLON.Tmp.Vector3[0];
  14780. var scale = BABYLON.Tmp.Vector3[1];
  14781. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14782. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14783. this.computeWorldMatrix(true);
  14784. node.computeWorldMatrix(true);
  14785. node.getWorldMatrix().invertToRef(invParentMatrix);
  14786. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14787. diffMatrix.decompose(scale, rotation, position);
  14788. if (this.rotationQuaternion) {
  14789. this.rotationQuaternion.copyFrom(rotation);
  14790. }
  14791. else {
  14792. rotation.toEulerAnglesToRef(this.rotation);
  14793. }
  14794. this.position.x = position.x;
  14795. this.position.y = position.y;
  14796. this.position.z = position.z;
  14797. this.scaling.x = scale.x;
  14798. this.scaling.y = scale.y;
  14799. this.scaling.z = scale.z;
  14800. }
  14801. this.parent = node;
  14802. return this;
  14803. };
  14804. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14805. get: function () {
  14806. return this._nonUniformScaling;
  14807. },
  14808. enumerable: true,
  14809. configurable: true
  14810. });
  14811. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14812. if (this._nonUniformScaling === value) {
  14813. return false;
  14814. }
  14815. this._nonUniformScaling = true;
  14816. return true;
  14817. };
  14818. /**
  14819. * Attach the current TransformNode to another TransformNode associated with a bone
  14820. * @param bone Bone affecting the TransformNode
  14821. * @param affectedTransformNode TransformNode associated with the bone
  14822. */
  14823. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14824. this._transformToBoneReferal = affectedTransformNode;
  14825. this.parent = bone;
  14826. if (bone.getWorldMatrix().determinant() < 0) {
  14827. this.scalingDeterminant *= -1;
  14828. }
  14829. return this;
  14830. };
  14831. TransformNode.prototype.detachFromBone = function () {
  14832. if (!this.parent) {
  14833. return this;
  14834. }
  14835. if (this.parent.getWorldMatrix().determinant() < 0) {
  14836. this.scalingDeterminant *= -1;
  14837. }
  14838. this._transformToBoneReferal = null;
  14839. this.parent = null;
  14840. return this;
  14841. };
  14842. /**
  14843. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14844. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14845. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14846. * The passed axis is also normalized.
  14847. * Returns the AbstractMesh.
  14848. */
  14849. TransformNode.prototype.rotate = function (axis, amount, space) {
  14850. axis.normalize();
  14851. if (!this.rotationQuaternion) {
  14852. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14853. this.rotation = BABYLON.Vector3.Zero();
  14854. }
  14855. var rotationQuaternion;
  14856. if (!space || space === BABYLON.Space.LOCAL) {
  14857. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14858. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14859. }
  14860. else {
  14861. if (this.parent) {
  14862. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14863. invertParentWorldMatrix.invert();
  14864. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14865. }
  14866. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14867. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14868. }
  14869. return this;
  14870. };
  14871. /**
  14872. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14873. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14874. * The passed axis is also normalized.
  14875. * Returns the AbstractMesh.
  14876. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14877. */
  14878. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14879. axis.normalize();
  14880. if (!this.rotationQuaternion) {
  14881. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14882. this.rotation.copyFromFloats(0, 0, 0);
  14883. }
  14884. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14885. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14886. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14887. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14888. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14889. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14890. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14891. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14892. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14893. return this;
  14894. };
  14895. /**
  14896. * Translates the mesh along the axis vector for the passed distance in the given space.
  14897. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14898. * Returns the AbstractMesh.
  14899. */
  14900. TransformNode.prototype.translate = function (axis, distance, space) {
  14901. var displacementVector = axis.scale(distance);
  14902. if (!space || space === BABYLON.Space.LOCAL) {
  14903. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14904. this.setPositionWithLocalVector(tempV3);
  14905. }
  14906. else {
  14907. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14908. }
  14909. return this;
  14910. };
  14911. /**
  14912. * Adds a rotation step to the mesh current rotation.
  14913. * x, y, z are Euler angles expressed in radians.
  14914. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14915. * This means this rotation is made in the mesh local space only.
  14916. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14917. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14918. * ```javascript
  14919. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14920. * ```
  14921. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14922. * 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.
  14923. * Returns the AbstractMesh.
  14924. */
  14925. TransformNode.prototype.addRotation = function (x, y, z) {
  14926. var rotationQuaternion;
  14927. if (this.rotationQuaternion) {
  14928. rotationQuaternion = this.rotationQuaternion;
  14929. }
  14930. else {
  14931. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14932. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14933. }
  14934. var accumulation = BABYLON.Tmp.Quaternion[0];
  14935. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14936. rotationQuaternion.multiplyInPlace(accumulation);
  14937. if (!this.rotationQuaternion) {
  14938. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14939. }
  14940. return this;
  14941. };
  14942. /**
  14943. * Computes the mesh World matrix and returns it.
  14944. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14945. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14946. * If the parameter `force`is set to `true`, the actual computation is done.
  14947. * Returns the mesh World Matrix.
  14948. */
  14949. TransformNode.prototype.computeWorldMatrix = function (force) {
  14950. if (this._isWorldMatrixFrozen) {
  14951. return this._worldMatrix;
  14952. }
  14953. if (!force && this.isSynchronized(true)) {
  14954. return this._worldMatrix;
  14955. }
  14956. this._cache.position.copyFrom(this.position);
  14957. this._cache.scaling.copyFrom(this.scaling);
  14958. this._cache.pivotMatrixUpdated = false;
  14959. this._cache.billboardMode = this.billboardMode;
  14960. this._currentRenderId = this.getScene().getRenderId();
  14961. this._isDirty = false;
  14962. // Scaling
  14963. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14964. // Rotation
  14965. //rotate, if quaternion is set and rotation was used
  14966. if (this.rotationQuaternion) {
  14967. var len = this.rotation.length();
  14968. if (len) {
  14969. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14970. this.rotation.copyFromFloats(0, 0, 0);
  14971. }
  14972. }
  14973. if (this.rotationQuaternion) {
  14974. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14975. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14976. }
  14977. else {
  14978. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14979. this._cache.rotation.copyFrom(this.rotation);
  14980. }
  14981. // Translation
  14982. var camera = this.getScene().activeCamera;
  14983. if (this.infiniteDistance && !this.parent && camera) {
  14984. var cameraWorldMatrix = camera.getWorldMatrix();
  14985. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14986. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14987. }
  14988. else {
  14989. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14990. }
  14991. // Composing transformations
  14992. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14993. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14994. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14995. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14996. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14997. // Need to decompose each rotation here
  14998. var currentPosition = BABYLON.Tmp.Vector3[3];
  14999. if (this.parent && this.parent.getWorldMatrix) {
  15000. if (this._transformToBoneReferal) {
  15001. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15002. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15003. }
  15004. else {
  15005. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15006. }
  15007. }
  15008. else {
  15009. currentPosition.copyFrom(this.position);
  15010. }
  15011. currentPosition.subtractInPlace(camera.globalPosition);
  15012. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15013. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15014. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15015. }
  15016. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15017. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15018. }
  15019. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15020. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15021. }
  15022. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15023. }
  15024. else {
  15025. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15026. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15027. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15028. }
  15029. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15030. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15031. }
  15032. // Local world
  15033. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15034. // Parent
  15035. if (this.parent && this.parent.getWorldMatrix) {
  15036. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15037. if (this._transformToBoneReferal) {
  15038. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15039. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15040. }
  15041. else {
  15042. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15043. }
  15044. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15045. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15046. this._worldMatrix.copyFrom(this._localWorld);
  15047. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15048. }
  15049. else {
  15050. if (this._transformToBoneReferal) {
  15051. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15052. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15053. }
  15054. else {
  15055. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15056. }
  15057. }
  15058. this._markSyncedWithParent();
  15059. }
  15060. else {
  15061. this._worldMatrix.copyFrom(this._localWorld);
  15062. }
  15063. // Post multiply inverse of pivotMatrix
  15064. if (this._postMultiplyPivotMatrix) {
  15065. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15066. }
  15067. // Normal matrix
  15068. if (this.scaling.isNonUniform) {
  15069. this._updateNonUniformScalingState(true);
  15070. }
  15071. else if (this.parent && this.parent._nonUniformScaling) {
  15072. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15073. }
  15074. else {
  15075. this._updateNonUniformScalingState(false);
  15076. }
  15077. this._afterComputeWorldMatrix();
  15078. // Absolute position
  15079. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15080. // Callbacks
  15081. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15082. if (!this._poseMatrix) {
  15083. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15084. }
  15085. // Cache the determinant
  15086. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15087. return this._worldMatrix;
  15088. };
  15089. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15090. };
  15091. /**
  15092. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15093. * @param func: callback function to add
  15094. *
  15095. * Returns the TransformNode.
  15096. */
  15097. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15098. this.onAfterWorldMatrixUpdateObservable.add(func);
  15099. return this;
  15100. };
  15101. /**
  15102. * Removes a registered callback function.
  15103. * Returns the TransformNode.
  15104. */
  15105. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15106. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15107. return this;
  15108. };
  15109. /**
  15110. * Clone the current transform node
  15111. * Returns the new transform node
  15112. * @param name Name of the new clone
  15113. * @param newParent New parent for the clone
  15114. * @param doNotCloneChildren Do not clone children hierarchy
  15115. */
  15116. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15117. var _this = this;
  15118. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15119. result.name = name;
  15120. result.id = name;
  15121. if (newParent) {
  15122. result.parent = newParent;
  15123. }
  15124. if (!doNotCloneChildren) {
  15125. // Children
  15126. var directDescendants = this.getDescendants(true);
  15127. for (var index = 0; index < directDescendants.length; index++) {
  15128. var child = directDescendants[index];
  15129. if (child.clone) {
  15130. child.clone(name + "." + child.name, result);
  15131. }
  15132. }
  15133. }
  15134. return result;
  15135. };
  15136. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15137. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15138. serializationObject.type = this.getClassName();
  15139. // Parent
  15140. if (this.parent) {
  15141. serializationObject.parentId = this.parent.id;
  15142. }
  15143. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15144. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15145. }
  15146. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15147. serializationObject.isEnabled = this.isEnabled();
  15148. // Parent
  15149. if (this.parent) {
  15150. serializationObject.parentId = this.parent.id;
  15151. }
  15152. return serializationObject;
  15153. };
  15154. // Statics
  15155. /**
  15156. * Returns a new TransformNode object parsed from the source provided.
  15157. * The parameter `parsedMesh` is the source.
  15158. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15159. */
  15160. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15161. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15162. if (BABYLON.Tags) {
  15163. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15164. }
  15165. if (parsedTransformNode.localMatrix) {
  15166. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15167. }
  15168. else if (parsedTransformNode.pivotMatrix) {
  15169. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15170. }
  15171. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15172. // Parent
  15173. if (parsedTransformNode.parentId) {
  15174. transformNode._waitingParentId = parsedTransformNode.parentId;
  15175. }
  15176. return transformNode;
  15177. };
  15178. /**
  15179. * Disposes the TransformNode.
  15180. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15181. * Returns nothing.
  15182. */
  15183. TransformNode.prototype.dispose = function (doNotRecurse) {
  15184. // Animations
  15185. this.getScene().stopAnimation(this);
  15186. // Remove from scene
  15187. this.getScene().removeTransformNode(this);
  15188. if (!doNotRecurse) {
  15189. // Children
  15190. var objects = this.getDescendants(true);
  15191. for (var index = 0; index < objects.length; index++) {
  15192. objects[index].dispose();
  15193. }
  15194. }
  15195. else {
  15196. var childMeshes = this.getChildMeshes(true);
  15197. for (index = 0; index < childMeshes.length; index++) {
  15198. var child = childMeshes[index];
  15199. child.parent = null;
  15200. child.computeWorldMatrix(true);
  15201. }
  15202. }
  15203. this.onAfterWorldMatrixUpdateObservable.clear();
  15204. _super.prototype.dispose.call(this);
  15205. };
  15206. // Statics
  15207. TransformNode.BILLBOARDMODE_NONE = 0;
  15208. TransformNode.BILLBOARDMODE_X = 1;
  15209. TransformNode.BILLBOARDMODE_Y = 2;
  15210. TransformNode.BILLBOARDMODE_Z = 4;
  15211. TransformNode.BILLBOARDMODE_ALL = 7;
  15212. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15213. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15214. __decorate([
  15215. BABYLON.serializeAsVector3()
  15216. ], TransformNode.prototype, "_rotation", void 0);
  15217. __decorate([
  15218. BABYLON.serializeAsQuaternion()
  15219. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15220. __decorate([
  15221. BABYLON.serializeAsVector3()
  15222. ], TransformNode.prototype, "_scaling", void 0);
  15223. __decorate([
  15224. BABYLON.serialize()
  15225. ], TransformNode.prototype, "billboardMode", void 0);
  15226. __decorate([
  15227. BABYLON.serialize()
  15228. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15229. __decorate([
  15230. BABYLON.serialize()
  15231. ], TransformNode.prototype, "infiniteDistance", void 0);
  15232. __decorate([
  15233. BABYLON.serializeAsVector3()
  15234. ], TransformNode.prototype, "position", void 0);
  15235. return TransformNode;
  15236. }(BABYLON.Node));
  15237. BABYLON.TransformNode = TransformNode;
  15238. })(BABYLON || (BABYLON = {}));
  15239. //# sourceMappingURL=babylon.transformNode.js.map
  15240. var BABYLON;
  15241. (function (BABYLON) {
  15242. var AbstractMesh = /** @class */ (function (_super) {
  15243. __extends(AbstractMesh, _super);
  15244. // Constructor
  15245. function AbstractMesh(name, scene) {
  15246. if (scene === void 0) { scene = null; }
  15247. var _this = _super.call(this, name, scene, false) || this;
  15248. _this._facetNb = 0; // facet number
  15249. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15250. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15251. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15252. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15253. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15254. _this._subDiv = {
  15255. max: 1,
  15256. X: 1,
  15257. Y: 1,
  15258. Z: 1
  15259. };
  15260. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15261. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15262. // Events
  15263. /**
  15264. * An event triggered when this mesh collides with another one
  15265. * @type {BABYLON.Observable}
  15266. */
  15267. _this.onCollideObservable = new BABYLON.Observable();
  15268. /**
  15269. * An event triggered when the collision's position changes
  15270. * @type {BABYLON.Observable}
  15271. */
  15272. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15273. /**
  15274. * An event triggered when material is changed
  15275. * @type {BABYLON.Observable}
  15276. */
  15277. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15278. // Properties
  15279. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15280. /**
  15281. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15282. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15283. * or
  15284. * 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.
  15285. * for more info check WebGl documentations
  15286. */
  15287. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15288. /**
  15289. * 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:
  15290. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15291. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15292. * 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.
  15293. */
  15294. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15295. /**
  15296. * 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.
  15297. * The default value is -1 which means don't break the query and wait till the result.
  15298. */
  15299. _this.occlusionRetryCount = -1;
  15300. _this._occlusionInternalRetryCounter = 0;
  15301. _this._isOccluded = false;
  15302. _this._isOcclusionQueryInProgress = false;
  15303. _this.visibility = 1.0;
  15304. _this.alphaIndex = Number.MAX_VALUE;
  15305. _this.isVisible = true;
  15306. _this.isPickable = true;
  15307. _this.showBoundingBox = false;
  15308. _this.showSubMeshesBoundingBox = false;
  15309. _this.isBlocker = false;
  15310. _this.enablePointerMoveEvents = false;
  15311. _this.renderingGroupId = 0;
  15312. _this._receiveShadows = false;
  15313. _this.renderOutline = false;
  15314. _this.outlineColor = BABYLON.Color3.Red();
  15315. _this.outlineWidth = 0.02;
  15316. _this.renderOverlay = false;
  15317. _this.overlayColor = BABYLON.Color3.Red();
  15318. _this.overlayAlpha = 0.5;
  15319. _this._hasVertexAlpha = false;
  15320. _this._useVertexColors = true;
  15321. _this._computeBonesUsingShaders = true;
  15322. _this._numBoneInfluencers = 4;
  15323. _this._applyFog = true;
  15324. _this.useOctreeForRenderingSelection = true;
  15325. _this.useOctreeForPicking = true;
  15326. _this.useOctreeForCollisions = true;
  15327. _this._layerMask = 0x0FFFFFFF;
  15328. /**
  15329. * True if the mesh must be rendered in any case.
  15330. */
  15331. _this.alwaysSelectAsActiveMesh = false;
  15332. /**
  15333. * This scene's action manager
  15334. * @type {BABYLON.ActionManager}
  15335. */
  15336. _this.actionManager = null;
  15337. // Physics
  15338. _this.physicsImpostor = null;
  15339. // Collisions
  15340. _this._checkCollisions = false;
  15341. _this._collisionMask = -1;
  15342. _this._collisionGroup = -1;
  15343. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15344. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15345. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15346. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15347. // Edges
  15348. _this.edgesWidth = 1;
  15349. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15350. // Cache
  15351. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15352. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15353. _this._isDisposed = false;
  15354. _this._renderId = 0;
  15355. _this._intersectionsInProgress = new Array();
  15356. _this._unIndexed = false;
  15357. _this._lightSources = new Array();
  15358. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15359. if (collidedMesh === void 0) { collidedMesh = null; }
  15360. //TODO move this to the collision coordinator!
  15361. if (_this.getScene().workerCollisions)
  15362. newPosition.multiplyInPlace(_this._collider._radius);
  15363. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15364. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15365. _this.position.addInPlace(_this._diffPositionForCollisions);
  15366. }
  15367. if (collidedMesh) {
  15368. _this.onCollideObservable.notifyObservers(collidedMesh);
  15369. }
  15370. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15371. };
  15372. _this.getScene().addMesh(_this);
  15373. _this._resyncLightSources();
  15374. return _this;
  15375. }
  15376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15377. get: function () {
  15378. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15379. },
  15380. enumerable: true,
  15381. configurable: true
  15382. });
  15383. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15384. get: function () {
  15385. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15391. get: function () {
  15392. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15398. get: function () {
  15399. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15405. get: function () {
  15406. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15407. },
  15408. enumerable: true,
  15409. configurable: true
  15410. });
  15411. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15412. /**
  15413. * Read-only : the number of facets in the mesh
  15414. */
  15415. get: function () {
  15416. return this._facetNb;
  15417. },
  15418. enumerable: true,
  15419. configurable: true
  15420. });
  15421. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15422. /**
  15423. * The number (integer) of subdivisions per axis in the partioning space
  15424. */
  15425. get: function () {
  15426. return this._partitioningSubdivisions;
  15427. },
  15428. set: function (nb) {
  15429. this._partitioningSubdivisions = nb;
  15430. },
  15431. enumerable: true,
  15432. configurable: true
  15433. });
  15434. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15435. /**
  15436. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15437. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15438. */
  15439. get: function () {
  15440. return this._partitioningBBoxRatio;
  15441. },
  15442. set: function (ratio) {
  15443. this._partitioningBBoxRatio = ratio;
  15444. },
  15445. enumerable: true,
  15446. configurable: true
  15447. });
  15448. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15449. /**
  15450. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15451. * Works only for updatable meshes.
  15452. * Doesn't work with multi-materials.
  15453. */
  15454. get: function () {
  15455. return this._facetDepthSort;
  15456. },
  15457. set: function (sort) {
  15458. this._facetDepthSort = sort;
  15459. },
  15460. enumerable: true,
  15461. configurable: true
  15462. });
  15463. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15464. /**
  15465. * The location (Vector3) where the facet depth sort must be computed from.
  15466. * By default, the active camera position.
  15467. * Used only when facet depth sort is enabled.
  15468. */
  15469. get: function () {
  15470. return this._facetDepthSortFrom;
  15471. },
  15472. set: function (location) {
  15473. this._facetDepthSortFrom = location;
  15474. },
  15475. enumerable: true,
  15476. configurable: true
  15477. });
  15478. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15479. /**
  15480. * Read-only boolean : is the feature facetData enabled ?
  15481. */
  15482. get: function () {
  15483. return this._facetDataEnabled;
  15484. },
  15485. enumerable: true,
  15486. configurable: true
  15487. });
  15488. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15489. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15490. return false;
  15491. }
  15492. this._markSubMeshesAsMiscDirty();
  15493. return true;
  15494. };
  15495. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15496. set: function (callback) {
  15497. if (this._onCollideObserver) {
  15498. this.onCollideObservable.remove(this._onCollideObserver);
  15499. }
  15500. this._onCollideObserver = this.onCollideObservable.add(callback);
  15501. },
  15502. enumerable: true,
  15503. configurable: true
  15504. });
  15505. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15506. set: function (callback) {
  15507. if (this._onCollisionPositionChangeObserver) {
  15508. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15509. }
  15510. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15511. },
  15512. enumerable: true,
  15513. configurable: true
  15514. });
  15515. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15516. /**
  15517. * 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.
  15518. */
  15519. get: function () {
  15520. return this._isOccluded;
  15521. },
  15522. set: function (value) {
  15523. this._isOccluded = value;
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15529. /**
  15530. * Flag to check the progress status of the query
  15531. */
  15532. get: function () {
  15533. return this._isOcclusionQueryInProgress;
  15534. },
  15535. enumerable: true,
  15536. configurable: true
  15537. });
  15538. Object.defineProperty(AbstractMesh.prototype, "material", {
  15539. get: function () {
  15540. return this._material;
  15541. },
  15542. set: function (value) {
  15543. if (this._material === value) {
  15544. return;
  15545. }
  15546. this._material = value;
  15547. if (this.onMaterialChangedObservable.hasObservers) {
  15548. this.onMaterialChangedObservable.notifyObservers(this);
  15549. }
  15550. if (!this.subMeshes) {
  15551. return;
  15552. }
  15553. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15554. var subMesh = _a[_i];
  15555. subMesh.setEffect(null);
  15556. }
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15562. get: function () {
  15563. return this._receiveShadows;
  15564. },
  15565. set: function (value) {
  15566. if (this._receiveShadows === value) {
  15567. return;
  15568. }
  15569. this._receiveShadows = value;
  15570. this._markSubMeshesAsLightDirty();
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15576. get: function () {
  15577. return this._hasVertexAlpha;
  15578. },
  15579. set: function (value) {
  15580. if (this._hasVertexAlpha === value) {
  15581. return;
  15582. }
  15583. this._hasVertexAlpha = value;
  15584. this._markSubMeshesAsAttributesDirty();
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15590. get: function () {
  15591. return this._useVertexColors;
  15592. },
  15593. set: function (value) {
  15594. if (this._useVertexColors === value) {
  15595. return;
  15596. }
  15597. this._useVertexColors = value;
  15598. this._markSubMeshesAsAttributesDirty();
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15604. get: function () {
  15605. return this._computeBonesUsingShaders;
  15606. },
  15607. set: function (value) {
  15608. if (this._computeBonesUsingShaders === value) {
  15609. return;
  15610. }
  15611. this._computeBonesUsingShaders = value;
  15612. this._markSubMeshesAsAttributesDirty();
  15613. },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15618. get: function () {
  15619. return this._numBoneInfluencers;
  15620. },
  15621. set: function (value) {
  15622. if (this._numBoneInfluencers === value) {
  15623. return;
  15624. }
  15625. this._numBoneInfluencers = value;
  15626. this._markSubMeshesAsAttributesDirty();
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15632. get: function () {
  15633. return this._applyFog;
  15634. },
  15635. set: function (value) {
  15636. if (this._applyFog === value) {
  15637. return;
  15638. }
  15639. this._applyFog = value;
  15640. this._markSubMeshesAsMiscDirty();
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15646. get: function () {
  15647. return this._layerMask;
  15648. },
  15649. set: function (value) {
  15650. if (value === this._layerMask) {
  15651. return;
  15652. }
  15653. this._layerMask = value;
  15654. this._resyncLightSources();
  15655. },
  15656. enumerable: true,
  15657. configurable: true
  15658. });
  15659. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15660. get: function () {
  15661. return this._collisionMask;
  15662. },
  15663. set: function (mask) {
  15664. this._collisionMask = !isNaN(mask) ? mask : -1;
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15670. get: function () {
  15671. return this._collisionGroup;
  15672. },
  15673. set: function (mask) {
  15674. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15675. },
  15676. enumerable: true,
  15677. configurable: true
  15678. });
  15679. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15680. get: function () {
  15681. return null;
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15687. get: function () {
  15688. return this._skeleton;
  15689. },
  15690. set: function (value) {
  15691. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15692. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15693. }
  15694. if (value && value.needInitialSkinMatrix) {
  15695. value._registerMeshWithPoseMatrix(this);
  15696. }
  15697. this._skeleton = value;
  15698. if (!this._skeleton) {
  15699. this._bonesTransformMatrices = null;
  15700. }
  15701. this._markSubMeshesAsAttributesDirty();
  15702. },
  15703. enumerable: true,
  15704. configurable: true
  15705. });
  15706. /**
  15707. * Boolean : true if the mesh has been disposed.
  15708. */
  15709. AbstractMesh.prototype.isDisposed = function () {
  15710. return this._isDisposed;
  15711. };
  15712. /**
  15713. * Returns the string "AbstractMesh"
  15714. */
  15715. AbstractMesh.prototype.getClassName = function () {
  15716. return "AbstractMesh";
  15717. };
  15718. /**
  15719. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15720. */
  15721. AbstractMesh.prototype.toString = function (fullDetails) {
  15722. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15723. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15724. if (this._skeleton) {
  15725. ret += ", skeleton: " + this._skeleton.name;
  15726. }
  15727. if (fullDetails) {
  15728. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15729. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15730. }
  15731. return ret;
  15732. };
  15733. AbstractMesh.prototype._rebuild = function () {
  15734. if (this._occlusionQuery) {
  15735. this._occlusionQuery = null;
  15736. }
  15737. if (this._edgesRenderer) {
  15738. this._edgesRenderer._rebuild();
  15739. }
  15740. if (!this.subMeshes) {
  15741. return;
  15742. }
  15743. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15744. var subMesh = _a[_i];
  15745. subMesh._rebuild();
  15746. }
  15747. };
  15748. AbstractMesh.prototype._resyncLightSources = function () {
  15749. this._lightSources.length = 0;
  15750. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15751. var light = _a[_i];
  15752. if (!light.isEnabled()) {
  15753. continue;
  15754. }
  15755. if (light.canAffectMesh(this)) {
  15756. this._lightSources.push(light);
  15757. }
  15758. }
  15759. this._markSubMeshesAsLightDirty();
  15760. };
  15761. AbstractMesh.prototype._resyncLighSource = function (light) {
  15762. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15763. var index = this._lightSources.indexOf(light);
  15764. if (index === -1) {
  15765. if (!isIn) {
  15766. return;
  15767. }
  15768. this._lightSources.push(light);
  15769. }
  15770. else {
  15771. if (isIn) {
  15772. return;
  15773. }
  15774. this._lightSources.splice(index, 1);
  15775. }
  15776. this._markSubMeshesAsLightDirty();
  15777. };
  15778. AbstractMesh.prototype._removeLightSource = function (light) {
  15779. var index = this._lightSources.indexOf(light);
  15780. if (index === -1) {
  15781. return;
  15782. }
  15783. this._lightSources.splice(index, 1);
  15784. };
  15785. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15786. if (!this.subMeshes) {
  15787. return;
  15788. }
  15789. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15790. var subMesh = _a[_i];
  15791. if (subMesh._materialDefines) {
  15792. func(subMesh._materialDefines);
  15793. }
  15794. }
  15795. };
  15796. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15797. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15798. };
  15799. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15800. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15801. };
  15802. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15803. if (!this.subMeshes) {
  15804. return;
  15805. }
  15806. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15807. var subMesh = _a[_i];
  15808. var material = subMesh.getMaterial();
  15809. if (material) {
  15810. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15811. }
  15812. }
  15813. };
  15814. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15815. /**
  15816. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15817. * Default : (1.0, 1.0, 1.0)
  15818. */
  15819. get: function () {
  15820. return this._scaling;
  15821. },
  15822. /**
  15823. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15824. * Default : (1.0, 1.0, 1.0)
  15825. */
  15826. set: function (newScaling) {
  15827. this._scaling = newScaling;
  15828. if (this.physicsImpostor) {
  15829. this.physicsImpostor.forceUpdate();
  15830. }
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. // Methods
  15836. /**
  15837. * Disables the mesh edger rendering mode.
  15838. * Returns the AbstractMesh.
  15839. */
  15840. AbstractMesh.prototype.disableEdgesRendering = function () {
  15841. if (this._edgesRenderer) {
  15842. this._edgesRenderer.dispose();
  15843. this._edgesRenderer = null;
  15844. }
  15845. return this;
  15846. };
  15847. /**
  15848. * Enables the edge rendering mode on the mesh.
  15849. * This mode makes the mesh edges visible.
  15850. * Returns the AbstractMesh.
  15851. */
  15852. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15853. if (epsilon === void 0) { epsilon = 0.95; }
  15854. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15855. this.disableEdgesRendering();
  15856. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15857. return this;
  15858. };
  15859. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15860. /**
  15861. * Returns true if the mesh is blocked. Used by the class Mesh.
  15862. * Returns the boolean `false` by default.
  15863. */
  15864. get: function () {
  15865. return false;
  15866. },
  15867. enumerable: true,
  15868. configurable: true
  15869. });
  15870. /**
  15871. * Returns the mesh itself by default, used by the class Mesh.
  15872. * Returned type : AbstractMesh
  15873. */
  15874. AbstractMesh.prototype.getLOD = function (camera) {
  15875. return this;
  15876. };
  15877. /**
  15878. * Returns 0 by default, used by the class Mesh.
  15879. * Returns an integer.
  15880. */
  15881. AbstractMesh.prototype.getTotalVertices = function () {
  15882. return 0;
  15883. };
  15884. /**
  15885. * Returns null by default, used by the class Mesh.
  15886. * Returned type : integer array
  15887. */
  15888. AbstractMesh.prototype.getIndices = function () {
  15889. return null;
  15890. };
  15891. /**
  15892. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15893. * Returned type : float array or Float32Array
  15894. */
  15895. AbstractMesh.prototype.getVerticesData = function (kind) {
  15896. return null;
  15897. };
  15898. /**
  15899. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15900. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15901. * The `data` are either a numeric array either a Float32Array.
  15902. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15903. * 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).
  15904. * Note that a new underlying VertexBuffer object is created each call.
  15905. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15906. *
  15907. * Possible `kind` values :
  15908. * - BABYLON.VertexBuffer.PositionKind
  15909. * - BABYLON.VertexBuffer.UVKind
  15910. * - BABYLON.VertexBuffer.UV2Kind
  15911. * - BABYLON.VertexBuffer.UV3Kind
  15912. * - BABYLON.VertexBuffer.UV4Kind
  15913. * - BABYLON.VertexBuffer.UV5Kind
  15914. * - BABYLON.VertexBuffer.UV6Kind
  15915. * - BABYLON.VertexBuffer.ColorKind
  15916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15920. *
  15921. * Returns the Mesh.
  15922. */
  15923. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15924. return this;
  15925. };
  15926. /**
  15927. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15928. * If the mesh has no geometry, it is simply returned as it is.
  15929. * The `data` are either a numeric array either a Float32Array.
  15930. * No new underlying VertexBuffer object is created.
  15931. * 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.
  15932. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15933. *
  15934. * Possible `kind` values :
  15935. * - BABYLON.VertexBuffer.PositionKind
  15936. * - BABYLON.VertexBuffer.UVKind
  15937. * - BABYLON.VertexBuffer.UV2Kind
  15938. * - BABYLON.VertexBuffer.UV3Kind
  15939. * - BABYLON.VertexBuffer.UV4Kind
  15940. * - BABYLON.VertexBuffer.UV5Kind
  15941. * - BABYLON.VertexBuffer.UV6Kind
  15942. * - BABYLON.VertexBuffer.ColorKind
  15943. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15944. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15945. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15946. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15947. *
  15948. * Returns the Mesh.
  15949. */
  15950. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15951. return this;
  15952. };
  15953. /**
  15954. * Sets the mesh indices.
  15955. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15956. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15957. * This method creates a new index buffer each call.
  15958. * Returns the Mesh.
  15959. */
  15960. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15961. return this;
  15962. };
  15963. /** Returns false by default, used by the class Mesh.
  15964. * Returns a boolean
  15965. */
  15966. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15967. return false;
  15968. };
  15969. /**
  15970. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15971. * Returns a BoundingInfo
  15972. */
  15973. AbstractMesh.prototype.getBoundingInfo = function () {
  15974. if (this._masterMesh) {
  15975. return this._masterMesh.getBoundingInfo();
  15976. }
  15977. if (!this._boundingInfo) {
  15978. // this._boundingInfo is being created here
  15979. this._updateBoundingInfo();
  15980. }
  15981. // cannot be null.
  15982. return this._boundingInfo;
  15983. };
  15984. /**
  15985. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15986. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15987. */
  15988. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15989. if (includeDescendants === void 0) { includeDescendants = true; }
  15990. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15991. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15992. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15993. if (maxDimension === 0) {
  15994. return this;
  15995. }
  15996. var scale = 1 / maxDimension;
  15997. this.scaling.scaleInPlace(scale);
  15998. return this;
  15999. };
  16000. /**
  16001. * Sets a mesh new object BoundingInfo.
  16002. * Returns the AbstractMesh.
  16003. */
  16004. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16005. this._boundingInfo = boundingInfo;
  16006. return this;
  16007. };
  16008. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16009. get: function () {
  16010. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. AbstractMesh.prototype._preActivate = function () {
  16016. };
  16017. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16018. };
  16019. AbstractMesh.prototype._activate = function (renderId) {
  16020. this._renderId = renderId;
  16021. };
  16022. /**
  16023. * Returns the latest update of the World matrix
  16024. * Returns a Matrix.
  16025. */
  16026. AbstractMesh.prototype.getWorldMatrix = function () {
  16027. if (this._masterMesh) {
  16028. return this._masterMesh.getWorldMatrix();
  16029. }
  16030. return _super.prototype.getWorldMatrix.call(this);
  16031. };
  16032. /**
  16033. * Returns the latest update of the World matrix determinant.
  16034. */
  16035. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16036. if (this._masterMesh) {
  16037. return this._masterMesh._getWorldMatrixDeterminant();
  16038. }
  16039. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16040. };
  16041. // ================================== Point of View Movement =================================
  16042. /**
  16043. * Perform relative position change from the point of view of behind the front of the mesh.
  16044. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16045. * Supports definition of mesh facing forward or backward.
  16046. * @param {number} amountRight
  16047. * @param {number} amountUp
  16048. * @param {number} amountForward
  16049. *
  16050. * Returns the AbstractMesh.
  16051. */
  16052. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16053. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16054. return this;
  16055. };
  16056. /**
  16057. * Calculate relative position change from the point of view of behind the front of the mesh.
  16058. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16059. * Supports definition of mesh facing forward or backward.
  16060. * @param {number} amountRight
  16061. * @param {number} amountUp
  16062. * @param {number} amountForward
  16063. *
  16064. * Returns a new Vector3.
  16065. */
  16066. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16067. var rotMatrix = new BABYLON.Matrix();
  16068. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16069. rotQuaternion.toRotationMatrix(rotMatrix);
  16070. var translationDelta = BABYLON.Vector3.Zero();
  16071. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16073. return translationDelta;
  16074. };
  16075. // ================================== Point of View Rotation =================================
  16076. /**
  16077. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16078. * Supports definition of mesh facing forward or backward.
  16079. * @param {number} flipBack
  16080. * @param {number} twirlClockwise
  16081. * @param {number} tiltRight
  16082. *
  16083. * Returns the AbstractMesh.
  16084. */
  16085. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16086. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16087. return this;
  16088. };
  16089. /**
  16090. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16091. * Supports definition of mesh facing forward or backward.
  16092. * @param {number} flipBack
  16093. * @param {number} twirlClockwise
  16094. * @param {number} tiltRight
  16095. *
  16096. * Returns a new Vector3.
  16097. */
  16098. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16099. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16100. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16101. };
  16102. /**
  16103. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16104. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16105. */
  16106. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16107. if (includeDescendants === void 0) { includeDescendants = true; }
  16108. this.computeWorldMatrix(true);
  16109. var min;
  16110. var max;
  16111. var boundingInfo = this.getBoundingInfo();
  16112. if (!this.subMeshes) {
  16113. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16114. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16115. }
  16116. else {
  16117. min = boundingInfo.boundingBox.minimumWorld;
  16118. max = boundingInfo.boundingBox.maximumWorld;
  16119. }
  16120. if (includeDescendants) {
  16121. var descendants = this.getDescendants(false);
  16122. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16123. var descendant = descendants_1[_i];
  16124. var childMesh = descendant;
  16125. childMesh.computeWorldMatrix(true);
  16126. //make sure we have the needed params to get mix and max
  16127. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16128. continue;
  16129. }
  16130. var childBoundingInfo = childMesh.getBoundingInfo();
  16131. var boundingBox = childBoundingInfo.boundingBox;
  16132. var minBox = boundingBox.minimumWorld;
  16133. var maxBox = boundingBox.maximumWorld;
  16134. BABYLON.Tools.CheckExtends(minBox, min, max);
  16135. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16136. }
  16137. }
  16138. return {
  16139. min: min,
  16140. max: max
  16141. };
  16142. };
  16143. /**
  16144. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16145. * Returns the AbstractMesh.
  16146. */
  16147. AbstractMesh.prototype._updateBoundingInfo = function () {
  16148. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16149. this._boundingInfo.update(this.worldMatrixFromCache);
  16150. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16151. return this;
  16152. };
  16153. /**
  16154. * Update a mesh's children BoundingInfo objects only.
  16155. * Returns the AbstractMesh.
  16156. */
  16157. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16158. if (!this.subMeshes) {
  16159. return this;
  16160. }
  16161. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16162. var subMesh = this.subMeshes[subIndex];
  16163. if (!subMesh.IsGlobal) {
  16164. subMesh.updateBoundingInfo(matrix);
  16165. }
  16166. }
  16167. return this;
  16168. };
  16169. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16170. // Bounding info
  16171. this._updateBoundingInfo();
  16172. };
  16173. /**
  16174. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16175. * A mesh is in the frustum if its bounding box intersects the frustum.
  16176. * Boolean returned.
  16177. */
  16178. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16179. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16180. };
  16181. /**
  16182. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16183. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16184. * Boolean returned.
  16185. */
  16186. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16187. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16188. ;
  16189. };
  16190. /**
  16191. * True if the mesh intersects another mesh or a SolidParticle object.
  16192. * 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)
  16193. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16194. * Returns a boolean.
  16195. */
  16196. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16197. if (precise === void 0) { precise = false; }
  16198. if (!this._boundingInfo || !mesh._boundingInfo) {
  16199. return false;
  16200. }
  16201. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16202. return true;
  16203. }
  16204. if (includeDescendants) {
  16205. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16206. var child = _a[_i];
  16207. if (child.intersectsMesh(mesh, precise, true)) {
  16208. return true;
  16209. }
  16210. }
  16211. }
  16212. return false;
  16213. };
  16214. /**
  16215. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16216. * Returns a boolean.
  16217. */
  16218. AbstractMesh.prototype.intersectsPoint = function (point) {
  16219. if (!this._boundingInfo) {
  16220. return false;
  16221. }
  16222. return this._boundingInfo.intersectsPoint(point);
  16223. };
  16224. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16225. return this.physicsImpostor;
  16226. };
  16227. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16228. if (camera === void 0) { camera = null; }
  16229. if (!camera) {
  16230. camera = this.getScene().activeCamera;
  16231. }
  16232. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16233. };
  16234. /**
  16235. * Returns the distance from the mesh to the active camera.
  16236. * Returns a float.
  16237. */
  16238. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16239. if (camera === void 0) { camera = null; }
  16240. if (!camera) {
  16241. camera = this.getScene().activeCamera;
  16242. }
  16243. return this.absolutePosition.subtract(camera.position).length();
  16244. };
  16245. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16246. if (!this.physicsImpostor) {
  16247. return this;
  16248. }
  16249. this.physicsImpostor.applyImpulse(force, contactPoint);
  16250. return this;
  16251. };
  16252. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16253. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16254. return this;
  16255. }
  16256. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16257. mainPivot: pivot1,
  16258. connectedPivot: pivot2,
  16259. nativeParams: options
  16260. });
  16261. return this;
  16262. };
  16263. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16264. // Collisions
  16265. /**
  16266. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16267. * Default `false`.
  16268. */
  16269. get: function () {
  16270. return this._checkCollisions;
  16271. },
  16272. set: function (collisionEnabled) {
  16273. this._checkCollisions = collisionEnabled;
  16274. if (this.getScene().workerCollisions) {
  16275. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16276. }
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16282. /**
  16283. * Gets Collider object used to compute collisions (not physics)
  16284. */
  16285. get: function () {
  16286. return this._collider;
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16292. var globalPosition = this.getAbsolutePosition();
  16293. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16294. if (!this._collider) {
  16295. this._collider = new BABYLON.Collider();
  16296. }
  16297. this._collider._radius = this.ellipsoid;
  16298. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16299. return this;
  16300. };
  16301. // Submeshes octree
  16302. /**
  16303. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16304. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16305. * Returns an Octree of submeshes.
  16306. */
  16307. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16308. if (maxCapacity === void 0) { maxCapacity = 64; }
  16309. if (maxDepth === void 0) { maxDepth = 2; }
  16310. if (!this._submeshesOctree) {
  16311. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16312. }
  16313. this.computeWorldMatrix(true);
  16314. var boundingInfo = this.getBoundingInfo();
  16315. // Update octree
  16316. var bbox = boundingInfo.boundingBox;
  16317. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16318. return this._submeshesOctree;
  16319. };
  16320. // Collisions
  16321. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16322. this._generatePointsArray();
  16323. if (!this._positions) {
  16324. return this;
  16325. }
  16326. // Transformation
  16327. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16328. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16329. subMesh._lastColliderWorldVertices = [];
  16330. subMesh._trianglePlanes = [];
  16331. var start = subMesh.verticesStart;
  16332. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16333. for (var i = start; i < end; i++) {
  16334. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16335. }
  16336. }
  16337. // Collide
  16338. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16339. if (collider.collisionFound) {
  16340. collider.collidedMesh = this;
  16341. }
  16342. return this;
  16343. };
  16344. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16345. var subMeshes;
  16346. var len;
  16347. // Octrees
  16348. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16349. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16350. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16351. len = intersections.length;
  16352. subMeshes = intersections.data;
  16353. }
  16354. else {
  16355. subMeshes = this.subMeshes;
  16356. len = subMeshes.length;
  16357. }
  16358. for (var index = 0; index < len; index++) {
  16359. var subMesh = subMeshes[index];
  16360. // Bounding test
  16361. if (len > 1 && !subMesh._checkCollision(collider))
  16362. continue;
  16363. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16364. }
  16365. return this;
  16366. };
  16367. AbstractMesh.prototype._checkCollision = function (collider) {
  16368. // Bounding box test
  16369. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16370. return this;
  16371. // Transformation matrix
  16372. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16373. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16374. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16375. return this;
  16376. };
  16377. // Picking
  16378. AbstractMesh.prototype._generatePointsArray = function () {
  16379. return false;
  16380. };
  16381. /**
  16382. * Checks if the passed Ray intersects with the mesh.
  16383. * Returns an object PickingInfo.
  16384. */
  16385. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16386. var pickingInfo = new BABYLON.PickingInfo();
  16387. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16388. return pickingInfo;
  16389. }
  16390. if (!this._generatePointsArray()) {
  16391. return pickingInfo;
  16392. }
  16393. var intersectInfo = null;
  16394. // Octrees
  16395. var subMeshes;
  16396. var len;
  16397. if (this._submeshesOctree && this.useOctreeForPicking) {
  16398. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16399. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16400. len = intersections.length;
  16401. subMeshes = intersections.data;
  16402. }
  16403. else {
  16404. subMeshes = this.subMeshes;
  16405. len = subMeshes.length;
  16406. }
  16407. for (var index = 0; index < len; index++) {
  16408. var subMesh = subMeshes[index];
  16409. // Bounding test
  16410. if (len > 1 && !subMesh.canIntersects(ray))
  16411. continue;
  16412. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16413. if (currentIntersectInfo) {
  16414. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16415. intersectInfo = currentIntersectInfo;
  16416. intersectInfo.subMeshId = index;
  16417. if (fastCheck) {
  16418. break;
  16419. }
  16420. }
  16421. }
  16422. }
  16423. if (intersectInfo) {
  16424. // Get picked point
  16425. var world = this.getWorldMatrix();
  16426. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16427. var direction = ray.direction.clone();
  16428. direction = direction.scale(intersectInfo.distance);
  16429. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16430. var pickedPoint = worldOrigin.add(worldDirection);
  16431. // Return result
  16432. pickingInfo.hit = true;
  16433. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16434. pickingInfo.pickedPoint = pickedPoint;
  16435. pickingInfo.pickedMesh = this;
  16436. pickingInfo.bu = intersectInfo.bu || 0;
  16437. pickingInfo.bv = intersectInfo.bv || 0;
  16438. pickingInfo.faceId = intersectInfo.faceId;
  16439. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16440. return pickingInfo;
  16441. }
  16442. return pickingInfo;
  16443. };
  16444. /**
  16445. * Clones the mesh, used by the class Mesh.
  16446. * Just returns `null` for an AbstractMesh.
  16447. */
  16448. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16449. return null;
  16450. };
  16451. /**
  16452. * Disposes all the mesh submeshes.
  16453. * Returns the AbstractMesh.
  16454. */
  16455. AbstractMesh.prototype.releaseSubMeshes = function () {
  16456. if (this.subMeshes) {
  16457. while (this.subMeshes.length) {
  16458. this.subMeshes[0].dispose();
  16459. }
  16460. }
  16461. else {
  16462. this.subMeshes = new Array();
  16463. }
  16464. return this;
  16465. };
  16466. /**
  16467. * Disposes the AbstractMesh.
  16468. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16469. * Returns nothing.
  16470. */
  16471. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16472. var _this = this;
  16473. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16474. var index;
  16475. // Action manager
  16476. if (this.actionManager !== undefined && this.actionManager !== null) {
  16477. this.actionManager.dispose();
  16478. this.actionManager = null;
  16479. }
  16480. // Skeleton
  16481. this.skeleton = null;
  16482. // Physics
  16483. if (this.physicsImpostor) {
  16484. this.physicsImpostor.dispose();
  16485. }
  16486. // Intersections in progress
  16487. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16488. var other = this._intersectionsInProgress[index];
  16489. var pos = other._intersectionsInProgress.indexOf(this);
  16490. other._intersectionsInProgress.splice(pos, 1);
  16491. }
  16492. this._intersectionsInProgress = [];
  16493. // Lights
  16494. var lights = this.getScene().lights;
  16495. lights.forEach(function (light) {
  16496. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16497. if (meshIndex !== -1) {
  16498. light.includedOnlyMeshes.splice(meshIndex, 1);
  16499. }
  16500. meshIndex = light.excludedMeshes.indexOf(_this);
  16501. if (meshIndex !== -1) {
  16502. light.excludedMeshes.splice(meshIndex, 1);
  16503. }
  16504. // Shadow generators
  16505. var generator = light.getShadowGenerator();
  16506. if (generator) {
  16507. var shadowMap = generator.getShadowMap();
  16508. if (shadowMap && shadowMap.renderList) {
  16509. meshIndex = shadowMap.renderList.indexOf(_this);
  16510. if (meshIndex !== -1) {
  16511. shadowMap.renderList.splice(meshIndex, 1);
  16512. }
  16513. }
  16514. }
  16515. });
  16516. // Edges
  16517. if (this._edgesRenderer) {
  16518. this._edgesRenderer.dispose();
  16519. this._edgesRenderer = null;
  16520. }
  16521. // SubMeshes
  16522. if (this.getClassName() !== "InstancedMesh") {
  16523. this.releaseSubMeshes();
  16524. }
  16525. // Octree
  16526. var sceneOctree = this.getScene().selectionOctree;
  16527. if (sceneOctree !== undefined && sceneOctree !== null) {
  16528. var index = sceneOctree.dynamicContent.indexOf(this);
  16529. if (index !== -1) {
  16530. sceneOctree.dynamicContent.splice(index, 1);
  16531. }
  16532. }
  16533. // Query
  16534. var engine = this.getScene().getEngine();
  16535. if (this._occlusionQuery) {
  16536. this._isOcclusionQueryInProgress = false;
  16537. engine.deleteQuery(this._occlusionQuery);
  16538. this._occlusionQuery = null;
  16539. }
  16540. // Engine
  16541. engine.wipeCaches();
  16542. // Remove from scene
  16543. this.getScene().removeMesh(this);
  16544. if (disposeMaterialAndTextures) {
  16545. if (this.material) {
  16546. this.material.dispose(false, true);
  16547. }
  16548. }
  16549. if (!doNotRecurse) {
  16550. // Particles
  16551. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16552. if (this.getScene().particleSystems[index].emitter === this) {
  16553. this.getScene().particleSystems[index].dispose();
  16554. index--;
  16555. }
  16556. }
  16557. }
  16558. // facet data
  16559. if (this._facetDataEnabled) {
  16560. this.disableFacetData();
  16561. }
  16562. this.onAfterWorldMatrixUpdateObservable.clear();
  16563. this.onCollideObservable.clear();
  16564. this.onCollisionPositionChangeObservable.clear();
  16565. this._isDisposed = true;
  16566. _super.prototype.dispose.call(this, doNotRecurse);
  16567. };
  16568. /**
  16569. * Adds the passed mesh as a child to the current mesh.
  16570. * Returns the AbstractMesh.
  16571. */
  16572. AbstractMesh.prototype.addChild = function (mesh) {
  16573. mesh.setParent(this);
  16574. return this;
  16575. };
  16576. /**
  16577. * Removes the passed mesh from the current mesh children list.
  16578. * Returns the AbstractMesh.
  16579. */
  16580. AbstractMesh.prototype.removeChild = function (mesh) {
  16581. mesh.setParent(null);
  16582. return this;
  16583. };
  16584. // Facet data
  16585. /**
  16586. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16587. * Returns the AbstractMesh.
  16588. */
  16589. AbstractMesh.prototype._initFacetData = function () {
  16590. if (!this._facetNormals) {
  16591. this._facetNormals = new Array();
  16592. }
  16593. if (!this._facetPositions) {
  16594. this._facetPositions = new Array();
  16595. }
  16596. if (!this._facetPartitioning) {
  16597. this._facetPartitioning = new Array();
  16598. }
  16599. this._facetNb = (this.getIndices().length / 3) | 0;
  16600. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16601. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16602. for (var f = 0; f < this._facetNb; f++) {
  16603. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16604. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16605. }
  16606. this._facetDataEnabled = true;
  16607. return this;
  16608. };
  16609. /**
  16610. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16611. * This method can be called within the render loop.
  16612. * 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.
  16613. * Returns the AbstractMesh.
  16614. */
  16615. AbstractMesh.prototype.updateFacetData = function () {
  16616. if (!this._facetDataEnabled) {
  16617. this._initFacetData();
  16618. }
  16619. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16620. var indices = this.getIndices();
  16621. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16622. var bInfo = this.getBoundingInfo();
  16623. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16624. // init arrays, matrix and sort function on first call
  16625. this._facetDepthSortEnabled = true;
  16626. if (indices instanceof Uint16Array) {
  16627. this._depthSortedIndices = new Uint16Array(indices);
  16628. }
  16629. else if (indices instanceof Uint32Array) {
  16630. this._depthSortedIndices = new Uint32Array(indices);
  16631. }
  16632. else {
  16633. var needs32bits = false;
  16634. for (var i = 0; i < indices.length; i++) {
  16635. if (indices[i] > 65535) {
  16636. needs32bits = true;
  16637. break;
  16638. }
  16639. }
  16640. if (needs32bits) {
  16641. this._depthSortedIndices = new Uint32Array(indices);
  16642. }
  16643. else {
  16644. this._depthSortedIndices = new Uint16Array(indices);
  16645. }
  16646. }
  16647. this._facetDepthSortFunction = function (f1, f2) {
  16648. return (f2.sqDistance - f1.sqDistance);
  16649. };
  16650. if (!this._facetDepthSortFrom) {
  16651. var camera = this.getScene().activeCamera;
  16652. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16653. }
  16654. this._depthSortedFacets = [];
  16655. for (var f = 0; f < this._facetNb; f++) {
  16656. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16657. this._depthSortedFacets.push(depthSortedFacet);
  16658. }
  16659. this._invertedMatrix = BABYLON.Matrix.Identity();
  16660. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16661. }
  16662. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16663. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16664. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16665. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16666. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16667. this._subDiv.max = this._partitioningSubdivisions;
  16668. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16669. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16670. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16671. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16672. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16673. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16674. // set the parameters for ComputeNormals()
  16675. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16676. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16677. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16678. this._facetParameters.bInfo = bInfo;
  16679. this._facetParameters.bbSize = this._bbSize;
  16680. this._facetParameters.subDiv = this._subDiv;
  16681. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16682. this._facetParameters.depthSort = this._facetDepthSort;
  16683. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16684. this.computeWorldMatrix(true);
  16685. this._worldMatrix.invertToRef(this._invertedMatrix);
  16686. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16687. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16688. }
  16689. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16690. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16691. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16692. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16693. var l = (this._depthSortedIndices.length / 3) | 0;
  16694. for (var f = 0; f < l; f++) {
  16695. var sind = this._depthSortedFacets[f].ind;
  16696. this._depthSortedIndices[f * 3] = indices[sind];
  16697. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16698. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16699. }
  16700. this.updateIndices(this._depthSortedIndices);
  16701. }
  16702. return this;
  16703. };
  16704. /**
  16705. * Returns the facetLocalNormals array.
  16706. * The normals are expressed in the mesh local space.
  16707. */
  16708. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16709. if (!this._facetNormals) {
  16710. this.updateFacetData();
  16711. }
  16712. return this._facetNormals;
  16713. };
  16714. /**
  16715. * Returns the facetLocalPositions array.
  16716. * The facet positions are expressed in the mesh local space.
  16717. */
  16718. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16719. if (!this._facetPositions) {
  16720. this.updateFacetData();
  16721. }
  16722. return this._facetPositions;
  16723. };
  16724. /**
  16725. * Returns the facetLocalPartioning array.
  16726. */
  16727. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16728. if (!this._facetPartitioning) {
  16729. this.updateFacetData();
  16730. }
  16731. return this._facetPartitioning;
  16732. };
  16733. /**
  16734. * Returns the i-th facet position in the world system.
  16735. * This method allocates a new Vector3 per call.
  16736. */
  16737. AbstractMesh.prototype.getFacetPosition = function (i) {
  16738. var pos = BABYLON.Vector3.Zero();
  16739. this.getFacetPositionToRef(i, pos);
  16740. return pos;
  16741. };
  16742. /**
  16743. * Sets the reference Vector3 with the i-th facet position in the world system.
  16744. * Returns the AbstractMesh.
  16745. */
  16746. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16747. var localPos = (this.getFacetLocalPositions())[i];
  16748. var world = this.getWorldMatrix();
  16749. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16750. return this;
  16751. };
  16752. /**
  16753. * Returns the i-th facet normal in the world system.
  16754. * This method allocates a new Vector3 per call.
  16755. */
  16756. AbstractMesh.prototype.getFacetNormal = function (i) {
  16757. var norm = BABYLON.Vector3.Zero();
  16758. this.getFacetNormalToRef(i, norm);
  16759. return norm;
  16760. };
  16761. /**
  16762. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16763. * Returns the AbstractMesh.
  16764. */
  16765. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16766. var localNorm = (this.getFacetLocalNormals())[i];
  16767. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16768. return this;
  16769. };
  16770. /**
  16771. * 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).
  16772. */
  16773. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16774. var bInfo = this.getBoundingInfo();
  16775. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16776. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16777. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16778. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16779. return null;
  16780. }
  16781. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16782. };
  16783. /**
  16784. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16785. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16786. * 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.
  16787. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16788. * 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.
  16789. */
  16790. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16791. if (checkFace === void 0) { checkFace = false; }
  16792. if (facing === void 0) { facing = true; }
  16793. var world = this.getWorldMatrix();
  16794. var invMat = BABYLON.Tmp.Matrix[5];
  16795. world.invertToRef(invMat);
  16796. var invVect = BABYLON.Tmp.Vector3[8];
  16797. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16798. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16799. if (projected) {
  16800. // tranform the local computed projected vector to world coordinates
  16801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16802. }
  16803. return closest;
  16804. };
  16805. /**
  16806. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16807. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16808. * 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.
  16809. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16810. * 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.
  16811. */
  16812. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16813. if (checkFace === void 0) { checkFace = false; }
  16814. if (facing === void 0) { facing = true; }
  16815. var closest = null;
  16816. var tmpx = 0.0;
  16817. var tmpy = 0.0;
  16818. var tmpz = 0.0;
  16819. var d = 0.0; // tmp dot facet normal * facet position
  16820. var t0 = 0.0;
  16821. var projx = 0.0;
  16822. var projy = 0.0;
  16823. var projz = 0.0;
  16824. // Get all the facets in the same partitioning block than (x, y, z)
  16825. var facetPositions = this.getFacetLocalPositions();
  16826. var facetNormals = this.getFacetLocalNormals();
  16827. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16828. if (!facetsInBlock) {
  16829. return null;
  16830. }
  16831. // Get the closest facet to (x, y, z)
  16832. var shortest = Number.MAX_VALUE; // init distance vars
  16833. var tmpDistance = shortest;
  16834. var fib; // current facet in the block
  16835. var norm; // current facet normal
  16836. var p0; // current facet barycenter position
  16837. // loop on all the facets in the current partitioning block
  16838. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16839. fib = facetsInBlock[idx];
  16840. norm = facetNormals[fib];
  16841. p0 = facetPositions[fib];
  16842. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16843. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16844. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16845. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16846. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16847. projx = x + norm.x * t0;
  16848. projy = y + norm.y * t0;
  16849. projz = z + norm.z * t0;
  16850. tmpx = projx - x;
  16851. tmpy = projy - y;
  16852. tmpz = projz - z;
  16853. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16854. if (tmpDistance < shortest) {
  16855. shortest = tmpDistance;
  16856. closest = fib;
  16857. if (projected) {
  16858. projected.x = projx;
  16859. projected.y = projy;
  16860. projected.z = projz;
  16861. }
  16862. }
  16863. }
  16864. }
  16865. return closest;
  16866. };
  16867. /**
  16868. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16869. */
  16870. AbstractMesh.prototype.getFacetDataParameters = function () {
  16871. return this._facetParameters;
  16872. };
  16873. /**
  16874. * Disables the feature FacetData and frees the related memory.
  16875. * Returns the AbstractMesh.
  16876. */
  16877. AbstractMesh.prototype.disableFacetData = function () {
  16878. if (this._facetDataEnabled) {
  16879. this._facetDataEnabled = false;
  16880. this._facetPositions = new Array();
  16881. this._facetNormals = new Array();
  16882. this._facetPartitioning = new Array();
  16883. this._facetParameters = null;
  16884. this._depthSortedIndices = new Uint32Array(0);
  16885. }
  16886. return this;
  16887. };
  16888. /**
  16889. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16890. * Returns the mesh.
  16891. */
  16892. AbstractMesh.prototype.updateIndices = function (indices) {
  16893. return this;
  16894. };
  16895. /**
  16896. * The mesh Geometry. Actually used by the Mesh object.
  16897. * Returns a blank geometry object.
  16898. */
  16899. /**
  16900. * Creates new normals data for the mesh.
  16901. * @param updatable.
  16902. */
  16903. AbstractMesh.prototype.createNormals = function (updatable) {
  16904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16905. var indices = this.getIndices();
  16906. var normals;
  16907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16908. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16909. }
  16910. else {
  16911. normals = [];
  16912. }
  16913. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16914. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16915. };
  16916. /**
  16917. * Align the mesh with a normal.
  16918. * Returns the mesh.
  16919. */
  16920. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16921. if (!upDirection) {
  16922. upDirection = BABYLON.Axis.Y;
  16923. }
  16924. var axisX = BABYLON.Tmp.Vector3[0];
  16925. var axisZ = BABYLON.Tmp.Vector3[1];
  16926. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16927. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16928. if (this.rotationQuaternion) {
  16929. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16930. }
  16931. else {
  16932. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16933. }
  16934. return this;
  16935. };
  16936. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16937. var engine = this.getEngine();
  16938. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16939. this._isOccluded = false;
  16940. return;
  16941. }
  16942. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16943. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16944. if (isOcclusionQueryAvailable) {
  16945. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16946. this._isOcclusionQueryInProgress = false;
  16947. this._occlusionInternalRetryCounter = 0;
  16948. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16949. }
  16950. else {
  16951. this._occlusionInternalRetryCounter++;
  16952. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16953. this._isOcclusionQueryInProgress = false;
  16954. this._occlusionInternalRetryCounter = 0;
  16955. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16956. // if strict continue the last state of the object.
  16957. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16958. }
  16959. else {
  16960. return;
  16961. }
  16962. }
  16963. }
  16964. var scene = this.getScene();
  16965. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16966. if (!this._occlusionQuery) {
  16967. this._occlusionQuery = engine.createQuery();
  16968. }
  16969. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16970. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16971. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16972. this._isOcclusionQueryInProgress = true;
  16973. };
  16974. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16975. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16976. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16977. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16978. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16979. return AbstractMesh;
  16980. }(BABYLON.TransformNode));
  16981. BABYLON.AbstractMesh = AbstractMesh;
  16982. })(BABYLON || (BABYLON = {}));
  16983. //# sourceMappingURL=babylon.abstractMesh.js.map
  16984. var BABYLON;
  16985. (function (BABYLON) {
  16986. var Light = /** @class */ (function (_super) {
  16987. __extends(Light, _super);
  16988. /**
  16989. * Creates a Light object in the scene.
  16990. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16991. */
  16992. function Light(name, scene) {
  16993. var _this = _super.call(this, name, scene) || this;
  16994. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16995. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16996. _this.intensity = 1.0;
  16997. _this.range = Number.MAX_VALUE;
  16998. /**
  16999. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17000. * of light.
  17001. */
  17002. _this._photometricScale = 1.0;
  17003. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17004. _this._radius = 0.00001;
  17005. _this.renderPriority = 0;
  17006. /**
  17007. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17008. * the current shadow generator.
  17009. */
  17010. _this.shadowEnabled = true;
  17011. _this._excludeWithLayerMask = 0;
  17012. _this._includeOnlyWithLayerMask = 0;
  17013. _this._lightmapMode = 0;
  17014. _this._excludedMeshesIds = new Array();
  17015. _this._includedOnlyMeshesIds = new Array();
  17016. _this.getScene().addLight(_this);
  17017. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17018. _this._buildUniformLayout();
  17019. _this.includedOnlyMeshes = new Array();
  17020. _this.excludedMeshes = new Array();
  17021. _this._resyncMeshes();
  17022. return _this;
  17023. }
  17024. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17025. /**
  17026. * If every light affecting the material is in this lightmapMode,
  17027. * material.lightmapTexture adds or multiplies
  17028. * (depends on material.useLightmapAsShadowmap)
  17029. * after every other light calculations.
  17030. */
  17031. get: function () {
  17032. return Light._LIGHTMAP_DEFAULT;
  17033. },
  17034. enumerable: true,
  17035. configurable: true
  17036. });
  17037. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17038. /**
  17039. * material.lightmapTexture as only diffuse lighting from this light
  17040. * adds only specular lighting from this light
  17041. * adds dynamic shadows
  17042. */
  17043. get: function () {
  17044. return Light._LIGHTMAP_SPECULAR;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17050. /**
  17051. * material.lightmapTexture as only lighting
  17052. * no light calculation from this light
  17053. * only adds dynamic shadows from this light
  17054. */
  17055. get: function () {
  17056. return Light._LIGHTMAP_SHADOWSONLY;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17062. /**
  17063. * Each light type uses the default quantity according to its type:
  17064. * point/spot lights use luminous intensity
  17065. * directional lights use illuminance
  17066. */
  17067. get: function () {
  17068. return Light._INTENSITYMODE_AUTOMATIC;
  17069. },
  17070. enumerable: true,
  17071. configurable: true
  17072. });
  17073. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17074. /**
  17075. * lumen (lm)
  17076. */
  17077. get: function () {
  17078. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17084. /**
  17085. * candela (lm/sr)
  17086. */
  17087. get: function () {
  17088. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17089. },
  17090. enumerable: true,
  17091. configurable: true
  17092. });
  17093. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17094. /**
  17095. * lux (lm/m^2)
  17096. */
  17097. get: function () {
  17098. return Light._INTENSITYMODE_ILLUMINANCE;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17104. /**
  17105. * nit (cd/m^2)
  17106. */
  17107. get: function () {
  17108. return Light._INTENSITYMODE_LUMINANCE;
  17109. },
  17110. enumerable: true,
  17111. configurable: true
  17112. });
  17113. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17114. /**
  17115. * Light type const id of the point light.
  17116. */
  17117. get: function () {
  17118. return Light._LIGHTTYPEID_POINTLIGHT;
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17124. /**
  17125. * Light type const id of the directional light.
  17126. */
  17127. get: function () {
  17128. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17129. },
  17130. enumerable: true,
  17131. configurable: true
  17132. });
  17133. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17134. /**
  17135. * Light type const id of the spot light.
  17136. */
  17137. get: function () {
  17138. return Light._LIGHTTYPEID_SPOTLIGHT;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17144. /**
  17145. * Light type const id of the hemispheric light.
  17146. */
  17147. get: function () {
  17148. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(Light.prototype, "intensityMode", {
  17154. /**
  17155. * Gets the photometric scale used to interpret the intensity.
  17156. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17157. */
  17158. get: function () {
  17159. return this._intensityMode;
  17160. },
  17161. /**
  17162. * Sets the photometric scale used to interpret the intensity.
  17163. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17164. */
  17165. set: function (value) {
  17166. this._intensityMode = value;
  17167. this._computePhotometricScale();
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. ;
  17173. ;
  17174. Object.defineProperty(Light.prototype, "radius", {
  17175. /**
  17176. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17177. */
  17178. get: function () {
  17179. return this._radius;
  17180. },
  17181. /**
  17182. * sets the light radius used by PBR Materials to simulate soft area lights.
  17183. */
  17184. set: function (value) {
  17185. this._radius = value;
  17186. this._computePhotometricScale();
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. ;
  17192. ;
  17193. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17194. get: function () {
  17195. return this._includedOnlyMeshes;
  17196. },
  17197. set: function (value) {
  17198. this._includedOnlyMeshes = value;
  17199. this._hookArrayForIncludedOnly(value);
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17205. get: function () {
  17206. return this._excludedMeshes;
  17207. },
  17208. set: function (value) {
  17209. this._excludedMeshes = value;
  17210. this._hookArrayForExcluded(value);
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17216. get: function () {
  17217. return this._excludeWithLayerMask;
  17218. },
  17219. set: function (value) {
  17220. this._excludeWithLayerMask = value;
  17221. this._resyncMeshes();
  17222. },
  17223. enumerable: true,
  17224. configurable: true
  17225. });
  17226. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17227. get: function () {
  17228. return this._includeOnlyWithLayerMask;
  17229. },
  17230. set: function (value) {
  17231. this._includeOnlyWithLayerMask = value;
  17232. this._resyncMeshes();
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Object.defineProperty(Light.prototype, "lightmapMode", {
  17238. get: function () {
  17239. return this._lightmapMode;
  17240. },
  17241. set: function (value) {
  17242. if (this._lightmapMode === value) {
  17243. return;
  17244. }
  17245. this._lightmapMode = value;
  17246. this._markMeshesAsLightDirty();
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. Light.prototype._buildUniformLayout = function () {
  17252. // Overridden
  17253. };
  17254. /**
  17255. * Returns the string "Light".
  17256. */
  17257. Light.prototype.getClassName = function () {
  17258. return "Light";
  17259. };
  17260. /**
  17261. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17262. */
  17263. Light.prototype.toString = function (fullDetails) {
  17264. var ret = "Name: " + this.name;
  17265. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17266. if (this.animations) {
  17267. for (var i = 0; i < this.animations.length; i++) {
  17268. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17269. }
  17270. }
  17271. if (fullDetails) {
  17272. }
  17273. return ret;
  17274. };
  17275. /**
  17276. * Set the enabled state of this node.
  17277. * @param {boolean} value - the new enabled state
  17278. * @see isEnabled
  17279. */
  17280. Light.prototype.setEnabled = function (value) {
  17281. _super.prototype.setEnabled.call(this, value);
  17282. this._resyncMeshes();
  17283. };
  17284. /**
  17285. * Returns the Light associated shadow generator.
  17286. */
  17287. Light.prototype.getShadowGenerator = function () {
  17288. return this._shadowGenerator;
  17289. };
  17290. /**
  17291. * Returns a Vector3, the absolute light position in the World.
  17292. */
  17293. Light.prototype.getAbsolutePosition = function () {
  17294. return BABYLON.Vector3.Zero();
  17295. };
  17296. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17297. };
  17298. Light.prototype._getWorldMatrix = function () {
  17299. return BABYLON.Matrix.Identity();
  17300. };
  17301. /**
  17302. * Boolean : True if the light will affect the passed mesh.
  17303. */
  17304. Light.prototype.canAffectMesh = function (mesh) {
  17305. if (!mesh) {
  17306. return true;
  17307. }
  17308. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17309. return false;
  17310. }
  17311. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17312. return false;
  17313. }
  17314. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17315. return false;
  17316. }
  17317. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17318. return false;
  17319. }
  17320. return true;
  17321. };
  17322. /**
  17323. * Returns the light World matrix.
  17324. */
  17325. Light.prototype.getWorldMatrix = function () {
  17326. this._currentRenderId = this.getScene().getRenderId();
  17327. var worldMatrix = this._getWorldMatrix();
  17328. if (this.parent && this.parent.getWorldMatrix) {
  17329. if (!this._parentedWorldMatrix) {
  17330. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17331. }
  17332. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17333. this._markSyncedWithParent();
  17334. return this._parentedWorldMatrix;
  17335. }
  17336. return worldMatrix;
  17337. };
  17338. /**
  17339. * Sort function to order lights for rendering.
  17340. * @param a First Light object to compare to second.
  17341. * @param b Second Light object to compare first.
  17342. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17343. */
  17344. Light.compareLightsPriority = function (a, b) {
  17345. //shadow-casting lights have priority over non-shadow-casting lights
  17346. //the renderPrioirty is a secondary sort criterion
  17347. if (a.shadowEnabled !== b.shadowEnabled) {
  17348. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17349. }
  17350. return b.renderPriority - a.renderPriority;
  17351. };
  17352. /**
  17353. * Disposes the light.
  17354. */
  17355. Light.prototype.dispose = function () {
  17356. if (this._shadowGenerator) {
  17357. this._shadowGenerator.dispose();
  17358. this._shadowGenerator = null;
  17359. }
  17360. // Animations
  17361. this.getScene().stopAnimation(this);
  17362. this._uniformBuffer.dispose();
  17363. // Remove from scene
  17364. this.getScene().removeLight(this);
  17365. _super.prototype.dispose.call(this);
  17366. };
  17367. /**
  17368. * Returns the light type ID (integer).
  17369. */
  17370. Light.prototype.getTypeID = function () {
  17371. return 0;
  17372. };
  17373. /**
  17374. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17375. */
  17376. Light.prototype.getScaledIntensity = function () {
  17377. return this._photometricScale * this.intensity;
  17378. };
  17379. /**
  17380. * Returns a new Light object, named "name", from the current one.
  17381. */
  17382. Light.prototype.clone = function (name) {
  17383. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17384. if (!constructor) {
  17385. return null;
  17386. }
  17387. return BABYLON.SerializationHelper.Clone(constructor, this);
  17388. };
  17389. /**
  17390. * Serializes the current light into a Serialization object.
  17391. * Returns the serialized object.
  17392. */
  17393. Light.prototype.serialize = function () {
  17394. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17395. // Type
  17396. serializationObject.type = this.getTypeID();
  17397. // Parent
  17398. if (this.parent) {
  17399. serializationObject.parentId = this.parent.id;
  17400. }
  17401. // Inclusion / exclusions
  17402. if (this.excludedMeshes.length > 0) {
  17403. serializationObject.excludedMeshesIds = [];
  17404. this.excludedMeshes.forEach(function (mesh) {
  17405. serializationObject.excludedMeshesIds.push(mesh.id);
  17406. });
  17407. }
  17408. if (this.includedOnlyMeshes.length > 0) {
  17409. serializationObject.includedOnlyMeshesIds = [];
  17410. this.includedOnlyMeshes.forEach(function (mesh) {
  17411. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17412. });
  17413. }
  17414. // Animations
  17415. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17416. serializationObject.ranges = this.serializeAnimationRanges();
  17417. return serializationObject;
  17418. };
  17419. /**
  17420. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17421. * This new light is named "name" and added to the passed scene.
  17422. */
  17423. Light.GetConstructorFromName = function (type, name, scene) {
  17424. switch (type) {
  17425. case 0:
  17426. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17427. case 1:
  17428. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17429. case 2:
  17430. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17431. case 3:
  17432. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17433. }
  17434. return null;
  17435. };
  17436. /**
  17437. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17438. */
  17439. Light.Parse = function (parsedLight, scene) {
  17440. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17441. if (!constructor) {
  17442. return null;
  17443. }
  17444. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17445. // Inclusion / exclusions
  17446. if (parsedLight.excludedMeshesIds) {
  17447. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17448. }
  17449. if (parsedLight.includedOnlyMeshesIds) {
  17450. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17451. }
  17452. // Parent
  17453. if (parsedLight.parentId) {
  17454. light._waitingParentId = parsedLight.parentId;
  17455. }
  17456. // Animations
  17457. if (parsedLight.animations) {
  17458. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17459. var parsedAnimation = parsedLight.animations[animationIndex];
  17460. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17461. }
  17462. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17463. }
  17464. if (parsedLight.autoAnimate) {
  17465. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17466. }
  17467. return light;
  17468. };
  17469. Light.prototype._hookArrayForExcluded = function (array) {
  17470. var _this = this;
  17471. var oldPush = array.push;
  17472. array.push = function () {
  17473. var items = [];
  17474. for (var _i = 0; _i < arguments.length; _i++) {
  17475. items[_i] = arguments[_i];
  17476. }
  17477. var result = oldPush.apply(array, items);
  17478. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17479. var item = items_1[_a];
  17480. item._resyncLighSource(_this);
  17481. }
  17482. return result;
  17483. };
  17484. var oldSplice = array.splice;
  17485. array.splice = function (index, deleteCount) {
  17486. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17487. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17488. var item = deleted_1[_i];
  17489. item._resyncLighSource(_this);
  17490. }
  17491. return deleted;
  17492. };
  17493. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17494. var item = array_1[_i];
  17495. item._resyncLighSource(this);
  17496. }
  17497. };
  17498. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17499. var _this = this;
  17500. var oldPush = array.push;
  17501. array.push = function () {
  17502. var items = [];
  17503. for (var _i = 0; _i < arguments.length; _i++) {
  17504. items[_i] = arguments[_i];
  17505. }
  17506. var result = oldPush.apply(array, items);
  17507. _this._resyncMeshes();
  17508. return result;
  17509. };
  17510. var oldSplice = array.splice;
  17511. array.splice = function (index, deleteCount) {
  17512. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17513. _this._resyncMeshes();
  17514. return deleted;
  17515. };
  17516. this._resyncMeshes();
  17517. };
  17518. Light.prototype._resyncMeshes = function () {
  17519. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17520. var mesh = _a[_i];
  17521. mesh._resyncLighSource(this);
  17522. }
  17523. };
  17524. Light.prototype._markMeshesAsLightDirty = function () {
  17525. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17526. var mesh = _a[_i];
  17527. if (mesh._lightSources.indexOf(this) !== -1) {
  17528. mesh._markSubMeshesAsLightDirty();
  17529. }
  17530. }
  17531. };
  17532. /**
  17533. * Recomputes the cached photometric scale if needed.
  17534. */
  17535. Light.prototype._computePhotometricScale = function () {
  17536. this._photometricScale = this._getPhotometricScale();
  17537. this.getScene().resetCachedMaterial();
  17538. };
  17539. /**
  17540. * Returns the Photometric Scale according to the light type and intensity mode.
  17541. */
  17542. Light.prototype._getPhotometricScale = function () {
  17543. var photometricScale = 0.0;
  17544. var lightTypeID = this.getTypeID();
  17545. //get photometric mode
  17546. var photometricMode = this.intensityMode;
  17547. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17548. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17549. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17550. }
  17551. else {
  17552. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17553. }
  17554. }
  17555. //compute photometric scale
  17556. switch (lightTypeID) {
  17557. case Light.LIGHTTYPEID_POINTLIGHT:
  17558. case Light.LIGHTTYPEID_SPOTLIGHT:
  17559. switch (photometricMode) {
  17560. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17561. photometricScale = 1.0 / (4.0 * Math.PI);
  17562. break;
  17563. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17564. photometricScale = 1.0;
  17565. break;
  17566. case Light.INTENSITYMODE_LUMINANCE:
  17567. photometricScale = this.radius * this.radius;
  17568. break;
  17569. }
  17570. break;
  17571. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17572. switch (photometricMode) {
  17573. case Light.INTENSITYMODE_ILLUMINANCE:
  17574. photometricScale = 1.0;
  17575. break;
  17576. case Light.INTENSITYMODE_LUMINANCE:
  17577. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17578. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17579. var apexAngleRadians = this.radius;
  17580. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17581. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17582. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17583. photometricScale = solidAngle;
  17584. break;
  17585. }
  17586. break;
  17587. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17588. // No fall off in hemisperic light.
  17589. photometricScale = 1.0;
  17590. break;
  17591. }
  17592. return photometricScale;
  17593. };
  17594. Light.prototype._reorderLightsInScene = function () {
  17595. var scene = this.getScene();
  17596. if (this._renderPriority != 0) {
  17597. scene.requireLightSorting = true;
  17598. }
  17599. this.getScene().sortLightsByPriority();
  17600. };
  17601. //lightmapMode Consts
  17602. Light._LIGHTMAP_DEFAULT = 0;
  17603. Light._LIGHTMAP_SPECULAR = 1;
  17604. Light._LIGHTMAP_SHADOWSONLY = 2;
  17605. // Intensity Mode Consts
  17606. Light._INTENSITYMODE_AUTOMATIC = 0;
  17607. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17608. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17609. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17610. Light._INTENSITYMODE_LUMINANCE = 4;
  17611. // Light types ids const.
  17612. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17613. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17614. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17615. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17616. __decorate([
  17617. BABYLON.serializeAsColor3()
  17618. ], Light.prototype, "diffuse", void 0);
  17619. __decorate([
  17620. BABYLON.serializeAsColor3()
  17621. ], Light.prototype, "specular", void 0);
  17622. __decorate([
  17623. BABYLON.serialize()
  17624. ], Light.prototype, "intensity", void 0);
  17625. __decorate([
  17626. BABYLON.serialize()
  17627. ], Light.prototype, "range", void 0);
  17628. __decorate([
  17629. BABYLON.serialize()
  17630. ], Light.prototype, "intensityMode", null);
  17631. __decorate([
  17632. BABYLON.serialize()
  17633. ], Light.prototype, "radius", null);
  17634. __decorate([
  17635. BABYLON.serialize()
  17636. ], Light.prototype, "_renderPriority", void 0);
  17637. __decorate([
  17638. BABYLON.expandToProperty("_reorderLightsInScene")
  17639. ], Light.prototype, "renderPriority", void 0);
  17640. __decorate([
  17641. BABYLON.serialize()
  17642. ], Light.prototype, "shadowEnabled", void 0);
  17643. __decorate([
  17644. BABYLON.serialize("excludeWithLayerMask")
  17645. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17646. __decorate([
  17647. BABYLON.serialize("includeOnlyWithLayerMask")
  17648. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17649. __decorate([
  17650. BABYLON.serialize("lightmapMode")
  17651. ], Light.prototype, "_lightmapMode", void 0);
  17652. return Light;
  17653. }(BABYLON.Node));
  17654. BABYLON.Light = Light;
  17655. })(BABYLON || (BABYLON = {}));
  17656. //# sourceMappingURL=babylon.light.js.map
  17657. var BABYLON;
  17658. (function (BABYLON) {
  17659. var Camera = /** @class */ (function (_super) {
  17660. __extends(Camera, _super);
  17661. function Camera(name, position, scene) {
  17662. var _this = _super.call(this, name, scene) || this;
  17663. _this.upVector = BABYLON.Vector3.Up();
  17664. _this.orthoLeft = null;
  17665. _this.orthoRight = null;
  17666. _this.orthoBottom = null;
  17667. _this.orthoTop = null;
  17668. /**
  17669. * default : 0.8
  17670. * FOV is set in Radians.
  17671. */
  17672. _this.fov = 0.8;
  17673. _this.minZ = 1;
  17674. _this.maxZ = 10000.0;
  17675. _this.inertia = 0.9;
  17676. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17677. _this.isIntermediate = false;
  17678. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17679. /**
  17680. * Restricts the camera to viewing objects with the same layerMask.
  17681. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17682. */
  17683. _this.layerMask = 0x0FFFFFFF;
  17684. /**
  17685. * default : FOVMODE_VERTICAL_FIXED
  17686. * fovMode sets the camera frustum bounds to the viewport bounds.
  17687. */
  17688. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17689. // Camera rig members
  17690. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17691. _this._rigCameras = new Array();
  17692. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17693. _this._skipRendering = false;
  17694. _this.customRenderTargets = new Array();
  17695. // Observables
  17696. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17697. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17698. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17699. _this.onRestoreStateObservable = new BABYLON.Observable();
  17700. // Cache
  17701. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17702. _this._projectionMatrix = new BABYLON.Matrix();
  17703. _this._doNotComputeProjectionMatrix = false;
  17704. _this._postProcesses = new Array();
  17705. _this._transformMatrix = BABYLON.Matrix.Zero();
  17706. _this._activeMeshes = new BABYLON.SmartArray(256);
  17707. _this._globalPosition = BABYLON.Vector3.Zero();
  17708. _this._refreshFrustumPlanes = true;
  17709. _this.getScene().addCamera(_this);
  17710. if (!_this.getScene().activeCamera) {
  17711. _this.getScene().activeCamera = _this;
  17712. }
  17713. _this.position = position;
  17714. return _this;
  17715. }
  17716. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17717. get: function () {
  17718. return Camera._PERSPECTIVE_CAMERA;
  17719. },
  17720. enumerable: true,
  17721. configurable: true
  17722. });
  17723. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17724. get: function () {
  17725. return Camera._ORTHOGRAPHIC_CAMERA;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17731. /**
  17732. * This is the default FOV mode for perspective cameras.
  17733. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17734. *
  17735. */
  17736. get: function () {
  17737. return Camera._FOVMODE_VERTICAL_FIXED;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17743. /**
  17744. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17745. *
  17746. */
  17747. get: function () {
  17748. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17754. get: function () {
  17755. return Camera._RIG_MODE_NONE;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17761. get: function () {
  17762. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17768. get: function () {
  17769. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17775. get: function () {
  17776. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17782. get: function () {
  17783. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17789. get: function () {
  17790. return Camera._RIG_MODE_VR;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17796. get: function () {
  17797. return Camera._RIG_MODE_WEBVR;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. /**
  17803. * Store current camera state (fov, position, etc..)
  17804. */
  17805. Camera.prototype.storeState = function () {
  17806. this._stateStored = true;
  17807. this._storedFov = this.fov;
  17808. return this;
  17809. };
  17810. /**
  17811. * Restores the camera state values if it has been stored. You must call storeState() first
  17812. */
  17813. Camera.prototype._restoreStateValues = function () {
  17814. if (!this._stateStored) {
  17815. return false;
  17816. }
  17817. this.fov = this._storedFov;
  17818. return true;
  17819. };
  17820. /**
  17821. * Restored camera state. You must call storeState() first
  17822. */
  17823. Camera.prototype.restoreState = function () {
  17824. if (this._restoreStateValues()) {
  17825. this.onRestoreStateObservable.notifyObservers(this);
  17826. return true;
  17827. }
  17828. return false;
  17829. };
  17830. Camera.prototype.getClassName = function () {
  17831. return "Camera";
  17832. };
  17833. /**
  17834. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17835. */
  17836. Camera.prototype.toString = function (fullDetails) {
  17837. var ret = "Name: " + this.name;
  17838. ret += ", type: " + this.getClassName();
  17839. if (this.animations) {
  17840. for (var i = 0; i < this.animations.length; i++) {
  17841. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17842. }
  17843. }
  17844. if (fullDetails) {
  17845. }
  17846. return ret;
  17847. };
  17848. Object.defineProperty(Camera.prototype, "globalPosition", {
  17849. get: function () {
  17850. return this._globalPosition;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Camera.prototype.getActiveMeshes = function () {
  17856. return this._activeMeshes;
  17857. };
  17858. Camera.prototype.isActiveMesh = function (mesh) {
  17859. return (this._activeMeshes.indexOf(mesh) !== -1);
  17860. };
  17861. //Cache
  17862. Camera.prototype._initCache = function () {
  17863. _super.prototype._initCache.call(this);
  17864. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17865. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17866. this._cache.mode = undefined;
  17867. this._cache.minZ = undefined;
  17868. this._cache.maxZ = undefined;
  17869. this._cache.fov = undefined;
  17870. this._cache.fovMode = undefined;
  17871. this._cache.aspectRatio = undefined;
  17872. this._cache.orthoLeft = undefined;
  17873. this._cache.orthoRight = undefined;
  17874. this._cache.orthoBottom = undefined;
  17875. this._cache.orthoTop = undefined;
  17876. this._cache.renderWidth = undefined;
  17877. this._cache.renderHeight = undefined;
  17878. };
  17879. Camera.prototype._updateCache = function (ignoreParentClass) {
  17880. if (!ignoreParentClass) {
  17881. _super.prototype._updateCache.call(this);
  17882. }
  17883. this._cache.position.copyFrom(this.position);
  17884. this._cache.upVector.copyFrom(this.upVector);
  17885. };
  17886. // Synchronized
  17887. Camera.prototype._isSynchronized = function () {
  17888. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17889. };
  17890. Camera.prototype._isSynchronizedViewMatrix = function () {
  17891. if (!_super.prototype._isSynchronized.call(this))
  17892. return false;
  17893. return this._cache.position.equals(this.position)
  17894. && this._cache.upVector.equals(this.upVector)
  17895. && this.isSynchronizedWithParent();
  17896. };
  17897. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17898. var check = this._cache.mode === this.mode
  17899. && this._cache.minZ === this.minZ
  17900. && this._cache.maxZ === this.maxZ;
  17901. if (!check) {
  17902. return false;
  17903. }
  17904. var engine = this.getEngine();
  17905. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17906. check = this._cache.fov === this.fov
  17907. && this._cache.fovMode === this.fovMode
  17908. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17909. }
  17910. else {
  17911. check = this._cache.orthoLeft === this.orthoLeft
  17912. && this._cache.orthoRight === this.orthoRight
  17913. && this._cache.orthoBottom === this.orthoBottom
  17914. && this._cache.orthoTop === this.orthoTop
  17915. && this._cache.renderWidth === engine.getRenderWidth()
  17916. && this._cache.renderHeight === engine.getRenderHeight();
  17917. }
  17918. return check;
  17919. };
  17920. // Controls
  17921. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17922. };
  17923. Camera.prototype.detachControl = function (element) {
  17924. };
  17925. Camera.prototype.update = function () {
  17926. this._checkInputs();
  17927. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17928. this._updateRigCameras();
  17929. }
  17930. };
  17931. Camera.prototype._checkInputs = function () {
  17932. this.onAfterCheckInputsObservable.notifyObservers(this);
  17933. };
  17934. Object.defineProperty(Camera.prototype, "rigCameras", {
  17935. get: function () {
  17936. return this._rigCameras;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17942. get: function () {
  17943. return this._rigPostProcess;
  17944. },
  17945. enumerable: true,
  17946. configurable: true
  17947. });
  17948. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17949. // invalidate framebuffer
  17950. if (this._postProcesses.length > 0) {
  17951. this._postProcesses[0].markTextureDirty();
  17952. }
  17953. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17954. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17955. var cam = this._rigCameras[i];
  17956. var rigPostProcess = cam._rigPostProcess;
  17957. // for VR rig, there does not have to be a post process
  17958. if (rigPostProcess) {
  17959. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17960. if (isPass) {
  17961. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17962. cam.isIntermediate = this._postProcesses.length === 0;
  17963. }
  17964. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17965. rigPostProcess.markTextureDirty();
  17966. }
  17967. else {
  17968. cam._postProcesses = this._postProcesses.slice(0);
  17969. }
  17970. }
  17971. };
  17972. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17973. if (insertAt === void 0) { insertAt = null; }
  17974. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17975. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17976. return 0;
  17977. }
  17978. if (insertAt == null || insertAt < 0) {
  17979. this._postProcesses.push(postProcess);
  17980. }
  17981. else {
  17982. this._postProcesses.splice(insertAt, 0, postProcess);
  17983. }
  17984. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17985. return this._postProcesses.indexOf(postProcess);
  17986. };
  17987. Camera.prototype.detachPostProcess = function (postProcess) {
  17988. var idx = this._postProcesses.indexOf(postProcess);
  17989. if (idx !== -1) {
  17990. this._postProcesses.splice(idx, 1);
  17991. }
  17992. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17993. };
  17994. Camera.prototype.getWorldMatrix = function () {
  17995. if (!this._worldMatrix) {
  17996. this._worldMatrix = BABYLON.Matrix.Identity();
  17997. }
  17998. var viewMatrix = this.getViewMatrix();
  17999. viewMatrix.invertToRef(this._worldMatrix);
  18000. return this._worldMatrix;
  18001. };
  18002. Camera.prototype._getViewMatrix = function () {
  18003. return BABYLON.Matrix.Identity();
  18004. };
  18005. Camera.prototype.getViewMatrix = function (force) {
  18006. if (!force && this._isSynchronizedViewMatrix()) {
  18007. return this._computedViewMatrix;
  18008. }
  18009. this.updateCache();
  18010. this._computedViewMatrix = this._getViewMatrix();
  18011. this._currentRenderId = this.getScene().getRenderId();
  18012. this._refreshFrustumPlanes = true;
  18013. if (!this.parent || !this.parent.getWorldMatrix) {
  18014. this._globalPosition.copyFrom(this.position);
  18015. }
  18016. else {
  18017. if (!this._worldMatrix) {
  18018. this._worldMatrix = BABYLON.Matrix.Identity();
  18019. }
  18020. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18021. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18022. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18023. this._computedViewMatrix.invert();
  18024. this._markSyncedWithParent();
  18025. }
  18026. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18027. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18028. }
  18029. this.onViewMatrixChangedObservable.notifyObservers(this);
  18030. return this._computedViewMatrix;
  18031. };
  18032. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18033. this._doNotComputeProjectionMatrix = true;
  18034. if (projection !== undefined) {
  18035. this._projectionMatrix = projection;
  18036. }
  18037. };
  18038. ;
  18039. Camera.prototype.unfreezeProjectionMatrix = function () {
  18040. this._doNotComputeProjectionMatrix = false;
  18041. };
  18042. ;
  18043. Camera.prototype.getProjectionMatrix = function (force) {
  18044. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18045. return this._projectionMatrix;
  18046. }
  18047. // Cache
  18048. this._cache.mode = this.mode;
  18049. this._cache.minZ = this.minZ;
  18050. this._cache.maxZ = this.maxZ;
  18051. // Matrix
  18052. this._refreshFrustumPlanes = true;
  18053. var engine = this.getEngine();
  18054. var scene = this.getScene();
  18055. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18056. this._cache.fov = this.fov;
  18057. this._cache.fovMode = this.fovMode;
  18058. this._cache.aspectRatio = engine.getAspectRatio(this);
  18059. if (this.minZ <= 0) {
  18060. this.minZ = 0.1;
  18061. }
  18062. if (scene.useRightHandedSystem) {
  18063. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18064. }
  18065. else {
  18066. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18067. }
  18068. }
  18069. else {
  18070. var halfWidth = engine.getRenderWidth() / 2.0;
  18071. var halfHeight = engine.getRenderHeight() / 2.0;
  18072. if (scene.useRightHandedSystem) {
  18073. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18074. }
  18075. else {
  18076. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18077. }
  18078. this._cache.orthoLeft = this.orthoLeft;
  18079. this._cache.orthoRight = this.orthoRight;
  18080. this._cache.orthoBottom = this.orthoBottom;
  18081. this._cache.orthoTop = this.orthoTop;
  18082. this._cache.renderWidth = engine.getRenderWidth();
  18083. this._cache.renderHeight = engine.getRenderHeight();
  18084. }
  18085. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18086. return this._projectionMatrix;
  18087. };
  18088. Camera.prototype.getTranformationMatrix = function () {
  18089. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18090. return this._transformMatrix;
  18091. };
  18092. Camera.prototype.updateFrustumPlanes = function () {
  18093. if (!this._refreshFrustumPlanes) {
  18094. return;
  18095. }
  18096. this.getTranformationMatrix();
  18097. if (!this._frustumPlanes) {
  18098. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18099. }
  18100. else {
  18101. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18102. }
  18103. this._refreshFrustumPlanes = false;
  18104. };
  18105. Camera.prototype.isInFrustum = function (target) {
  18106. this.updateFrustumPlanes();
  18107. return target.isInFrustum(this._frustumPlanes);
  18108. };
  18109. Camera.prototype.isCompletelyInFrustum = function (target) {
  18110. this.updateFrustumPlanes();
  18111. return target.isCompletelyInFrustum(this._frustumPlanes);
  18112. };
  18113. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18114. if (length === void 0) { length = 100; }
  18115. if (!transform) {
  18116. transform = this.getWorldMatrix();
  18117. }
  18118. if (!origin) {
  18119. origin = this.position;
  18120. }
  18121. var forward = new BABYLON.Vector3(0, 0, 1);
  18122. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18123. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18124. return new BABYLON.Ray(origin, direction, length);
  18125. };
  18126. Camera.prototype.dispose = function () {
  18127. // Observables
  18128. this.onViewMatrixChangedObservable.clear();
  18129. this.onProjectionMatrixChangedObservable.clear();
  18130. this.onAfterCheckInputsObservable.clear();
  18131. this.onRestoreStateObservable.clear();
  18132. // Inputs
  18133. if (this.inputs) {
  18134. this.inputs.clear();
  18135. }
  18136. // Animations
  18137. this.getScene().stopAnimation(this);
  18138. // Remove from scene
  18139. this.getScene().removeCamera(this);
  18140. while (this._rigCameras.length > 0) {
  18141. var camera = this._rigCameras.pop();
  18142. if (camera) {
  18143. camera.dispose();
  18144. }
  18145. }
  18146. // Postprocesses
  18147. if (this._rigPostProcess) {
  18148. this._rigPostProcess.dispose(this);
  18149. this._rigPostProcess = null;
  18150. this._postProcesses = [];
  18151. }
  18152. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18153. this._rigPostProcess = null;
  18154. this._postProcesses = [];
  18155. }
  18156. else {
  18157. var i = this._postProcesses.length;
  18158. while (--i >= 0) {
  18159. this._postProcesses[i].dispose(this);
  18160. }
  18161. }
  18162. // Render targets
  18163. var i = this.customRenderTargets.length;
  18164. while (--i >= 0) {
  18165. this.customRenderTargets[i].dispose();
  18166. }
  18167. this.customRenderTargets = [];
  18168. // Active Meshes
  18169. this._activeMeshes.dispose();
  18170. _super.prototype.dispose.call(this);
  18171. };
  18172. Object.defineProperty(Camera.prototype, "leftCamera", {
  18173. // ---- Camera rigs section ----
  18174. get: function () {
  18175. if (this._rigCameras.length < 1) {
  18176. return null;
  18177. }
  18178. return this._rigCameras[0];
  18179. },
  18180. enumerable: true,
  18181. configurable: true
  18182. });
  18183. Object.defineProperty(Camera.prototype, "rightCamera", {
  18184. get: function () {
  18185. if (this._rigCameras.length < 2) {
  18186. return null;
  18187. }
  18188. return this._rigCameras[1];
  18189. },
  18190. enumerable: true,
  18191. configurable: true
  18192. });
  18193. Camera.prototype.getLeftTarget = function () {
  18194. if (this._rigCameras.length < 1) {
  18195. return null;
  18196. }
  18197. return this._rigCameras[0].getTarget();
  18198. };
  18199. Camera.prototype.getRightTarget = function () {
  18200. if (this._rigCameras.length < 2) {
  18201. return null;
  18202. }
  18203. return this._rigCameras[1].getTarget();
  18204. };
  18205. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18206. if (this.cameraRigMode === mode) {
  18207. return;
  18208. }
  18209. while (this._rigCameras.length > 0) {
  18210. var camera = this._rigCameras.pop();
  18211. if (camera) {
  18212. camera.dispose();
  18213. }
  18214. }
  18215. this.cameraRigMode = mode;
  18216. this._cameraRigParams = {};
  18217. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18218. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18219. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18220. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18221. // create the rig cameras, unless none
  18222. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18223. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18224. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18225. if (leftCamera && rightCamera) {
  18226. this._rigCameras.push(leftCamera);
  18227. this._rigCameras.push(rightCamera);
  18228. }
  18229. }
  18230. switch (this.cameraRigMode) {
  18231. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18232. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18233. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18234. break;
  18235. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18236. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18237. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18238. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18239. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18240. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18241. break;
  18242. case Camera.RIG_MODE_VR:
  18243. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18244. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18245. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18247. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18248. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18249. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18250. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18251. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18252. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18253. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18254. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18255. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18256. if (metrics.compensateDistortion) {
  18257. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18258. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18259. }
  18260. break;
  18261. case Camera.RIG_MODE_WEBVR:
  18262. if (rigParams.vrDisplay) {
  18263. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18264. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18265. //Left eye
  18266. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18267. this._rigCameras[0].setCameraRigParameter("left", true);
  18268. //leaving this for future reference
  18269. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18270. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18271. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18272. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18273. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18274. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18275. this._rigCameras[0].parent = this;
  18276. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18277. //Right eye
  18278. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18279. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18280. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18281. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18282. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18283. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18284. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18285. this._rigCameras[1].parent = this;
  18286. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18287. if (Camera.UseAlternateWebVRRendering) {
  18288. this._rigCameras[1]._skipRendering = true;
  18289. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18290. }
  18291. }
  18292. break;
  18293. }
  18294. this._cascadePostProcessesToRigCams();
  18295. this.update();
  18296. };
  18297. Camera.prototype._getVRProjectionMatrix = function () {
  18298. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18299. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18300. return this._projectionMatrix;
  18301. };
  18302. Camera.prototype._updateCameraRotationMatrix = function () {
  18303. //Here for WebVR
  18304. };
  18305. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18306. //Here for WebVR
  18307. };
  18308. /**
  18309. * This function MUST be overwritten by the different WebVR cameras available.
  18310. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18311. */
  18312. Camera.prototype._getWebVRProjectionMatrix = function () {
  18313. return BABYLON.Matrix.Identity();
  18314. };
  18315. /**
  18316. * This function MUST be overwritten by the different WebVR cameras available.
  18317. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18318. */
  18319. Camera.prototype._getWebVRViewMatrix = function () {
  18320. return BABYLON.Matrix.Identity();
  18321. };
  18322. Camera.prototype.setCameraRigParameter = function (name, value) {
  18323. if (!this._cameraRigParams) {
  18324. this._cameraRigParams = {};
  18325. }
  18326. this._cameraRigParams[name] = value;
  18327. //provisionnally:
  18328. if (name === "interaxialDistance") {
  18329. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18330. }
  18331. };
  18332. /**
  18333. * needs to be overridden by children so sub has required properties to be copied
  18334. */
  18335. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18336. return null;
  18337. };
  18338. /**
  18339. * May need to be overridden by children
  18340. */
  18341. Camera.prototype._updateRigCameras = function () {
  18342. for (var i = 0; i < this._rigCameras.length; i++) {
  18343. this._rigCameras[i].minZ = this.minZ;
  18344. this._rigCameras[i].maxZ = this.maxZ;
  18345. this._rigCameras[i].fov = this.fov;
  18346. }
  18347. // only update viewport when ANAGLYPH
  18348. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18349. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18350. }
  18351. };
  18352. Camera.prototype._setupInputs = function () {
  18353. };
  18354. Camera.prototype.serialize = function () {
  18355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18356. // Type
  18357. serializationObject.type = this.getClassName();
  18358. // Parent
  18359. if (this.parent) {
  18360. serializationObject.parentId = this.parent.id;
  18361. }
  18362. if (this.inputs) {
  18363. this.inputs.serialize(serializationObject);
  18364. }
  18365. // Animations
  18366. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18367. serializationObject.ranges = this.serializeAnimationRanges();
  18368. return serializationObject;
  18369. };
  18370. Camera.prototype.clone = function (name) {
  18371. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18372. };
  18373. Camera.prototype.getDirection = function (localAxis) {
  18374. var result = BABYLON.Vector3.Zero();
  18375. this.getDirectionToRef(localAxis, result);
  18376. return result;
  18377. };
  18378. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18379. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18380. };
  18381. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18382. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18383. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18384. switch (type) {
  18385. case "ArcRotateCamera":
  18386. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18387. case "DeviceOrientationCamera":
  18388. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18389. case "FollowCamera":
  18390. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18391. case "ArcFollowCamera":
  18392. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18393. case "GamepadCamera":
  18394. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18395. case "TouchCamera":
  18396. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18397. case "VirtualJoysticksCamera":
  18398. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18399. case "WebVRFreeCamera":
  18400. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18401. case "WebVRGamepadCamera":
  18402. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18403. case "VRDeviceOrientationFreeCamera":
  18404. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18405. case "VRDeviceOrientationGamepadCamera":
  18406. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18407. case "AnaglyphArcRotateCamera":
  18408. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18409. case "AnaglyphFreeCamera":
  18410. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18411. case "AnaglyphGamepadCamera":
  18412. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18413. case "AnaglyphUniversalCamera":
  18414. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18415. case "StereoscopicArcRotateCamera":
  18416. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18417. case "StereoscopicFreeCamera":
  18418. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18419. case "StereoscopicGamepadCamera":
  18420. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18421. case "StereoscopicUniversalCamera":
  18422. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18423. case "FreeCamera":// Forcing Universal here
  18424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18425. default:// Universal Camera is the default value
  18426. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18427. }
  18428. };
  18429. Camera.prototype.computeWorldMatrix = function () {
  18430. return this.getWorldMatrix();
  18431. };
  18432. Camera.Parse = function (parsedCamera, scene) {
  18433. var type = parsedCamera.type;
  18434. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18435. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18436. // Parent
  18437. if (parsedCamera.parentId) {
  18438. camera._waitingParentId = parsedCamera.parentId;
  18439. }
  18440. //If camera has an input manager, let it parse inputs settings
  18441. if (camera.inputs) {
  18442. camera.inputs.parse(parsedCamera);
  18443. camera._setupInputs();
  18444. }
  18445. if (camera.setPosition) {
  18446. camera.position.copyFromFloats(0, 0, 0);
  18447. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18448. }
  18449. // Target
  18450. if (parsedCamera.target) {
  18451. if (camera.setTarget) {
  18452. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18453. }
  18454. }
  18455. // Apply 3d rig, when found
  18456. if (parsedCamera.cameraRigMode) {
  18457. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18458. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18459. }
  18460. // Animations
  18461. if (parsedCamera.animations) {
  18462. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18463. var parsedAnimation = parsedCamera.animations[animationIndex];
  18464. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18465. }
  18466. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18467. }
  18468. if (parsedCamera.autoAnimate) {
  18469. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18470. }
  18471. return camera;
  18472. };
  18473. // Statics
  18474. Camera._PERSPECTIVE_CAMERA = 0;
  18475. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18476. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18477. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18478. Camera._RIG_MODE_NONE = 0;
  18479. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18480. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18481. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18482. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18483. Camera._RIG_MODE_VR = 20;
  18484. Camera._RIG_MODE_WEBVR = 21;
  18485. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18486. Camera.UseAlternateWebVRRendering = false;
  18487. __decorate([
  18488. BABYLON.serializeAsVector3()
  18489. ], Camera.prototype, "position", void 0);
  18490. __decorate([
  18491. BABYLON.serializeAsVector3()
  18492. ], Camera.prototype, "upVector", void 0);
  18493. __decorate([
  18494. BABYLON.serialize()
  18495. ], Camera.prototype, "orthoLeft", void 0);
  18496. __decorate([
  18497. BABYLON.serialize()
  18498. ], Camera.prototype, "orthoRight", void 0);
  18499. __decorate([
  18500. BABYLON.serialize()
  18501. ], Camera.prototype, "orthoBottom", void 0);
  18502. __decorate([
  18503. BABYLON.serialize()
  18504. ], Camera.prototype, "orthoTop", void 0);
  18505. __decorate([
  18506. BABYLON.serialize()
  18507. ], Camera.prototype, "fov", void 0);
  18508. __decorate([
  18509. BABYLON.serialize()
  18510. ], Camera.prototype, "minZ", void 0);
  18511. __decorate([
  18512. BABYLON.serialize()
  18513. ], Camera.prototype, "maxZ", void 0);
  18514. __decorate([
  18515. BABYLON.serialize()
  18516. ], Camera.prototype, "inertia", void 0);
  18517. __decorate([
  18518. BABYLON.serialize()
  18519. ], Camera.prototype, "mode", void 0);
  18520. __decorate([
  18521. BABYLON.serialize()
  18522. ], Camera.prototype, "layerMask", void 0);
  18523. __decorate([
  18524. BABYLON.serialize()
  18525. ], Camera.prototype, "fovMode", void 0);
  18526. __decorate([
  18527. BABYLON.serialize()
  18528. ], Camera.prototype, "cameraRigMode", void 0);
  18529. __decorate([
  18530. BABYLON.serialize()
  18531. ], Camera.prototype, "interaxialDistance", void 0);
  18532. __decorate([
  18533. BABYLON.serialize()
  18534. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18535. return Camera;
  18536. }(BABYLON.Node));
  18537. BABYLON.Camera = Camera;
  18538. })(BABYLON || (BABYLON = {}));
  18539. //# sourceMappingURL=babylon.camera.js.map
  18540. var BABYLON;
  18541. (function (BABYLON) {
  18542. var RenderingManager = /** @class */ (function () {
  18543. function RenderingManager(scene) {
  18544. this._renderingGroups = new Array();
  18545. this._autoClearDepthStencil = {};
  18546. this._customOpaqueSortCompareFn = {};
  18547. this._customAlphaTestSortCompareFn = {};
  18548. this._customTransparentSortCompareFn = {};
  18549. this._renderinGroupInfo = null;
  18550. this._scene = scene;
  18551. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18552. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18553. }
  18554. }
  18555. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18556. if (depth === void 0) { depth = true; }
  18557. if (stencil === void 0) { stencil = true; }
  18558. if (this._depthStencilBufferAlreadyCleaned) {
  18559. return;
  18560. }
  18561. this._scene.getEngine().clear(null, false, depth, stencil);
  18562. this._depthStencilBufferAlreadyCleaned = true;
  18563. };
  18564. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18565. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18566. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18567. var info = null;
  18568. if (observable) {
  18569. if (!this._renderinGroupInfo) {
  18570. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18571. }
  18572. info = this._renderinGroupInfo;
  18573. info.scene = this._scene;
  18574. info.camera = this._scene.activeCamera;
  18575. }
  18576. // Dispatch sprites
  18577. if (renderSprites) {
  18578. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18579. var manager = this._scene.spriteManagers[index];
  18580. this.dispatchSprites(manager);
  18581. }
  18582. }
  18583. // Render
  18584. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18585. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18586. var renderingGroup = this._renderingGroups[index];
  18587. if (!renderingGroup && !observable)
  18588. continue;
  18589. var renderingGroupMask = 0;
  18590. // Fire PRECLEAR stage
  18591. if (observable && info) {
  18592. renderingGroupMask = Math.pow(2, index);
  18593. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18594. info.renderingGroupId = index;
  18595. observable.notifyObservers(info, renderingGroupMask);
  18596. }
  18597. // Clear depth/stencil if needed
  18598. if (RenderingManager.AUTOCLEAR) {
  18599. var autoClear = this._autoClearDepthStencil[index];
  18600. if (autoClear && autoClear.autoClear) {
  18601. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18602. }
  18603. }
  18604. if (observable && info) {
  18605. // Fire PREOPAQUE stage
  18606. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18607. observable.notifyObservers(info, renderingGroupMask);
  18608. // Fire PRETRANSPARENT stage
  18609. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18610. observable.notifyObservers(info, renderingGroupMask);
  18611. }
  18612. if (renderingGroup)
  18613. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18614. // Fire POSTTRANSPARENT stage
  18615. if (observable && info) {
  18616. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18617. observable.notifyObservers(info, renderingGroupMask);
  18618. }
  18619. }
  18620. };
  18621. RenderingManager.prototype.reset = function () {
  18622. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18623. var renderingGroup = this._renderingGroups[index];
  18624. if (renderingGroup) {
  18625. renderingGroup.prepare();
  18626. }
  18627. }
  18628. };
  18629. RenderingManager.prototype.dispose = function () {
  18630. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18631. var renderingGroup = this._renderingGroups[index];
  18632. if (renderingGroup) {
  18633. renderingGroup.dispose();
  18634. }
  18635. }
  18636. this._renderingGroups.length = 0;
  18637. };
  18638. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18639. if (this._renderingGroups[renderingGroupId] === undefined) {
  18640. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18641. }
  18642. };
  18643. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18644. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18645. this._prepareRenderingGroup(renderingGroupId);
  18646. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18647. };
  18648. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18649. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18650. this._prepareRenderingGroup(renderingGroupId);
  18651. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18652. };
  18653. /**
  18654. * @param subMesh The submesh to dispatch
  18655. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18656. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18657. */
  18658. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18659. if (mesh === undefined) {
  18660. mesh = subMesh.getMesh();
  18661. }
  18662. var renderingGroupId = mesh.renderingGroupId || 0;
  18663. this._prepareRenderingGroup(renderingGroupId);
  18664. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18665. };
  18666. /**
  18667. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18668. * This allowed control for front to back rendering or reversly depending of the special needs.
  18669. *
  18670. * @param renderingGroupId The rendering group id corresponding to its index
  18671. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18672. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18673. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18674. */
  18675. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18676. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18677. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18678. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18679. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18680. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18681. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18682. if (this._renderingGroups[renderingGroupId]) {
  18683. var group = this._renderingGroups[renderingGroupId];
  18684. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18685. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18686. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18687. }
  18688. };
  18689. /**
  18690. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18691. *
  18692. * @param renderingGroupId The rendering group id corresponding to its index
  18693. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18694. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18695. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18696. */
  18697. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18698. if (depth === void 0) { depth = true; }
  18699. if (stencil === void 0) { stencil = true; }
  18700. this._autoClearDepthStencil[renderingGroupId] = {
  18701. autoClear: autoClearDepthStencil,
  18702. depth: depth,
  18703. stencil: stencil
  18704. };
  18705. };
  18706. /**
  18707. * The max id used for rendering groups (not included)
  18708. */
  18709. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18710. /**
  18711. * The min id used for rendering groups (included)
  18712. */
  18713. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18714. /**
  18715. * Used to globally prevent autoclearing scenes.
  18716. */
  18717. RenderingManager.AUTOCLEAR = true;
  18718. return RenderingManager;
  18719. }());
  18720. BABYLON.RenderingManager = RenderingManager;
  18721. })(BABYLON || (BABYLON = {}));
  18722. //# sourceMappingURL=babylon.renderingManager.js.map
  18723. var BABYLON;
  18724. (function (BABYLON) {
  18725. var RenderingGroup = /** @class */ (function () {
  18726. /**
  18727. * Creates a new rendering group.
  18728. * @param index The rendering group index
  18729. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18730. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18731. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18732. */
  18733. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18734. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18735. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18736. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18737. this.index = index;
  18738. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18739. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18740. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18741. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18742. this._particleSystems = new BABYLON.SmartArray(256);
  18743. this._spriteManagers = new BABYLON.SmartArray(256);
  18744. this._edgesRenderers = new BABYLON.SmartArray(16);
  18745. this._scene = scene;
  18746. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18747. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18748. this.transparentSortCompareFn = transparentSortCompareFn;
  18749. }
  18750. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18751. /**
  18752. * Set the opaque sort comparison function.
  18753. * If null the sub meshes will be render in the order they were created
  18754. */
  18755. set: function (value) {
  18756. this._opaqueSortCompareFn = value;
  18757. if (value) {
  18758. this._renderOpaque = this.renderOpaqueSorted;
  18759. }
  18760. else {
  18761. this._renderOpaque = RenderingGroup.renderUnsorted;
  18762. }
  18763. },
  18764. enumerable: true,
  18765. configurable: true
  18766. });
  18767. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18768. /**
  18769. * Set the alpha test sort comparison function.
  18770. * If null the sub meshes will be render in the order they were created
  18771. */
  18772. set: function (value) {
  18773. this._alphaTestSortCompareFn = value;
  18774. if (value) {
  18775. this._renderAlphaTest = this.renderAlphaTestSorted;
  18776. }
  18777. else {
  18778. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18779. }
  18780. },
  18781. enumerable: true,
  18782. configurable: true
  18783. });
  18784. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18785. /**
  18786. * Set the transparent sort comparison function.
  18787. * If null the sub meshes will be render in the order they were created
  18788. */
  18789. set: function (value) {
  18790. if (value) {
  18791. this._transparentSortCompareFn = value;
  18792. }
  18793. else {
  18794. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18795. }
  18796. this._renderTransparent = this.renderTransparentSorted;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. /**
  18802. * Render all the sub meshes contained in the group.
  18803. * @param customRenderFunction Used to override the default render behaviour of the group.
  18804. * @returns true if rendered some submeshes.
  18805. */
  18806. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18807. if (customRenderFunction) {
  18808. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18809. return;
  18810. }
  18811. var engine = this._scene.getEngine();
  18812. // Depth only
  18813. if (this._depthOnlySubMeshes.length !== 0) {
  18814. engine.setAlphaTesting(true);
  18815. engine.setColorWrite(false);
  18816. this._renderAlphaTest(this._depthOnlySubMeshes);
  18817. engine.setAlphaTesting(false);
  18818. engine.setColorWrite(true);
  18819. }
  18820. // Opaque
  18821. if (this._opaqueSubMeshes.length !== 0) {
  18822. this._renderOpaque(this._opaqueSubMeshes);
  18823. }
  18824. // Alpha test
  18825. if (this._alphaTestSubMeshes.length !== 0) {
  18826. engine.setAlphaTesting(true);
  18827. this._renderAlphaTest(this._alphaTestSubMeshes);
  18828. engine.setAlphaTesting(false);
  18829. }
  18830. var stencilState = engine.getStencilBuffer();
  18831. engine.setStencilBuffer(false);
  18832. // Sprites
  18833. if (renderSprites) {
  18834. this._renderSprites();
  18835. }
  18836. // Particles
  18837. if (renderParticles) {
  18838. this._renderParticles(activeMeshes);
  18839. }
  18840. if (this.onBeforeTransparentRendering) {
  18841. this.onBeforeTransparentRendering();
  18842. }
  18843. // Transparent
  18844. if (this._transparentSubMeshes.length !== 0) {
  18845. this._renderTransparent(this._transparentSubMeshes);
  18846. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18847. }
  18848. // Set back stencil to false in case it changes before the edge renderer.
  18849. engine.setStencilBuffer(false);
  18850. // Edges
  18851. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18852. this._edgesRenderers.data[edgesRendererIndex].render();
  18853. }
  18854. // Restore Stencil state.
  18855. engine.setStencilBuffer(stencilState);
  18856. };
  18857. /**
  18858. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18859. * @param subMeshes The submeshes to render
  18860. */
  18861. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18862. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18863. };
  18864. /**
  18865. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18866. * @param subMeshes The submeshes to render
  18867. */
  18868. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18869. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18870. };
  18871. /**
  18872. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18873. * @param subMeshes The submeshes to render
  18874. */
  18875. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18876. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18877. };
  18878. /**
  18879. * Renders the submeshes in a specified order.
  18880. * @param subMeshes The submeshes to sort before render
  18881. * @param sortCompareFn The comparison function use to sort
  18882. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18883. * @param transparent Specifies to activate blending if true
  18884. */
  18885. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18886. var subIndex = 0;
  18887. var subMesh;
  18888. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18889. for (; subIndex < subMeshes.length; subIndex++) {
  18890. subMesh = subMeshes.data[subIndex];
  18891. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18892. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18893. }
  18894. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18895. if (sortCompareFn) {
  18896. sortedArray.sort(sortCompareFn);
  18897. }
  18898. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18899. subMesh = sortedArray[subIndex];
  18900. if (transparent) {
  18901. var material = subMesh.getMaterial();
  18902. if (material && material.needDepthPrePass) {
  18903. var engine = material.getScene().getEngine();
  18904. engine.setColorWrite(false);
  18905. engine.setAlphaTesting(true);
  18906. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18907. subMesh.render(false);
  18908. engine.setAlphaTesting(false);
  18909. engine.setColorWrite(true);
  18910. }
  18911. }
  18912. subMesh.render(transparent);
  18913. }
  18914. };
  18915. /**
  18916. * Renders the submeshes in the order they were dispatched (no sort applied).
  18917. * @param subMeshes The submeshes to render
  18918. */
  18919. RenderingGroup.renderUnsorted = function (subMeshes) {
  18920. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18921. var submesh = subMeshes.data[subIndex];
  18922. submesh.render(false);
  18923. }
  18924. };
  18925. /**
  18926. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18927. * are rendered back to front if in the same alpha index.
  18928. *
  18929. * @param a The first submesh
  18930. * @param b The second submesh
  18931. * @returns The result of the comparison
  18932. */
  18933. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18934. // Alpha index first
  18935. if (a._alphaIndex > b._alphaIndex) {
  18936. return 1;
  18937. }
  18938. if (a._alphaIndex < b._alphaIndex) {
  18939. return -1;
  18940. }
  18941. // Then distance to camera
  18942. return RenderingGroup.backToFrontSortCompare(a, b);
  18943. };
  18944. /**
  18945. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18946. * are rendered back to front.
  18947. *
  18948. * @param a The first submesh
  18949. * @param b The second submesh
  18950. * @returns The result of the comparison
  18951. */
  18952. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18953. // Then distance to camera
  18954. if (a._distanceToCamera < b._distanceToCamera) {
  18955. return 1;
  18956. }
  18957. if (a._distanceToCamera > b._distanceToCamera) {
  18958. return -1;
  18959. }
  18960. return 0;
  18961. };
  18962. /**
  18963. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18964. * are rendered front to back (prevent overdraw).
  18965. *
  18966. * @param a The first submesh
  18967. * @param b The second submesh
  18968. * @returns The result of the comparison
  18969. */
  18970. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18971. // Then distance to camera
  18972. if (a._distanceToCamera < b._distanceToCamera) {
  18973. return -1;
  18974. }
  18975. if (a._distanceToCamera > b._distanceToCamera) {
  18976. return 1;
  18977. }
  18978. return 0;
  18979. };
  18980. /**
  18981. * Resets the different lists of submeshes to prepare a new frame.
  18982. */
  18983. RenderingGroup.prototype.prepare = function () {
  18984. this._opaqueSubMeshes.reset();
  18985. this._transparentSubMeshes.reset();
  18986. this._alphaTestSubMeshes.reset();
  18987. this._depthOnlySubMeshes.reset();
  18988. this._particleSystems.reset();
  18989. this._spriteManagers.reset();
  18990. this._edgesRenderers.reset();
  18991. };
  18992. RenderingGroup.prototype.dispose = function () {
  18993. this._opaqueSubMeshes.dispose();
  18994. this._transparentSubMeshes.dispose();
  18995. this._alphaTestSubMeshes.dispose();
  18996. this._depthOnlySubMeshes.dispose();
  18997. this._particleSystems.dispose();
  18998. this._spriteManagers.dispose();
  18999. this._edgesRenderers.dispose();
  19000. };
  19001. /**
  19002. * Inserts the submesh in its correct queue depending on its material.
  19003. * @param subMesh The submesh to dispatch
  19004. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19005. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19006. */
  19007. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19008. // Get mesh and materials if not provided
  19009. if (mesh === undefined) {
  19010. mesh = subMesh.getMesh();
  19011. }
  19012. if (material === undefined) {
  19013. material = subMesh.getMaterial();
  19014. }
  19015. if (material === null || material === undefined) {
  19016. return;
  19017. }
  19018. if (material.needAlphaBlendingForMesh(mesh)) {
  19019. this._transparentSubMeshes.push(subMesh);
  19020. }
  19021. else if (material.needAlphaTesting()) {
  19022. if (material.needDepthPrePass) {
  19023. this._depthOnlySubMeshes.push(subMesh);
  19024. }
  19025. this._alphaTestSubMeshes.push(subMesh);
  19026. }
  19027. else {
  19028. if (material.needDepthPrePass) {
  19029. this._depthOnlySubMeshes.push(subMesh);
  19030. }
  19031. this._opaqueSubMeshes.push(subMesh); // Opaque
  19032. }
  19033. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19034. this._edgesRenderers.push(mesh._edgesRenderer);
  19035. }
  19036. };
  19037. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19038. this._spriteManagers.push(spriteManager);
  19039. };
  19040. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19041. this._particleSystems.push(particleSystem);
  19042. };
  19043. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19044. if (this._particleSystems.length === 0) {
  19045. return;
  19046. }
  19047. // Particles
  19048. var activeCamera = this._scene.activeCamera;
  19049. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19050. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19051. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19052. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19053. continue;
  19054. }
  19055. var emitter = particleSystem.emitter;
  19056. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19057. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19058. }
  19059. }
  19060. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19061. };
  19062. RenderingGroup.prototype._renderSprites = function () {
  19063. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19064. return;
  19065. }
  19066. // Sprites
  19067. var activeCamera = this._scene.activeCamera;
  19068. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19069. for (var id = 0; id < this._spriteManagers.length; id++) {
  19070. var spriteManager = this._spriteManagers.data[id];
  19071. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19072. spriteManager.render();
  19073. }
  19074. }
  19075. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19076. };
  19077. return RenderingGroup;
  19078. }());
  19079. BABYLON.RenderingGroup = RenderingGroup;
  19080. })(BABYLON || (BABYLON = {}));
  19081. //# sourceMappingURL=babylon.renderingGroup.js.map
  19082. var BABYLON;
  19083. (function (BABYLON) {
  19084. var ClickInfo = /** @class */ (function () {
  19085. function ClickInfo() {
  19086. this._singleClick = false;
  19087. this._doubleClick = false;
  19088. this._hasSwiped = false;
  19089. this._ignore = false;
  19090. }
  19091. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19092. get: function () {
  19093. return this._singleClick;
  19094. },
  19095. set: function (b) {
  19096. this._singleClick = b;
  19097. },
  19098. enumerable: true,
  19099. configurable: true
  19100. });
  19101. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19102. get: function () {
  19103. return this._doubleClick;
  19104. },
  19105. set: function (b) {
  19106. this._doubleClick = b;
  19107. },
  19108. enumerable: true,
  19109. configurable: true
  19110. });
  19111. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19112. get: function () {
  19113. return this._hasSwiped;
  19114. },
  19115. set: function (b) {
  19116. this._hasSwiped = b;
  19117. },
  19118. enumerable: true,
  19119. configurable: true
  19120. });
  19121. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19122. get: function () {
  19123. return this._ignore;
  19124. },
  19125. set: function (b) {
  19126. this._ignore = b;
  19127. },
  19128. enumerable: true,
  19129. configurable: true
  19130. });
  19131. return ClickInfo;
  19132. }());
  19133. /**
  19134. * This class is used by the onRenderingGroupObservable
  19135. */
  19136. var RenderingGroupInfo = /** @class */ (function () {
  19137. function RenderingGroupInfo() {
  19138. }
  19139. /**
  19140. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19141. * This stage will be fired no matter what
  19142. */
  19143. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19144. /**
  19145. * Called before opaque object are rendered.
  19146. * This stage will be fired only if there's 3D Opaque content to render
  19147. */
  19148. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19149. /**
  19150. * Called after the opaque objects are rendered and before the transparent ones
  19151. * This stage will be fired only if there's 3D transparent content to render
  19152. */
  19153. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19154. /**
  19155. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19156. * This stage will be fired no matter what
  19157. */
  19158. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19159. return RenderingGroupInfo;
  19160. }());
  19161. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19162. /**
  19163. * Represents a scene to be rendered by the engine.
  19164. * @see http://doc.babylonjs.com/page.php?p=21911
  19165. */
  19166. var Scene = /** @class */ (function () {
  19167. /**
  19168. * @constructor
  19169. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19170. */
  19171. function Scene(engine) {
  19172. // Members
  19173. this.autoClear = true;
  19174. this.autoClearDepthAndStencil = true;
  19175. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19176. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19177. this.forceWireframe = false;
  19178. this._forcePointsCloud = false;
  19179. this.forceShowBoundingBoxes = false;
  19180. this.animationsEnabled = true;
  19181. this.useConstantAnimationDeltaTime = false;
  19182. this.constantlyUpdateMeshUnderPointer = false;
  19183. this.hoverCursor = "pointer";
  19184. this.defaultCursor = "";
  19185. /**
  19186. * This is used to call preventDefault() on pointer down
  19187. * in order to block unwanted artifacts like system double clicks
  19188. */
  19189. this.preventDefaultOnPointerDown = true;
  19190. // Metadata
  19191. this.metadata = null;
  19192. /**
  19193. * An event triggered when the scene is disposed.
  19194. * @type {BABYLON.Observable}
  19195. */
  19196. this.onDisposeObservable = new BABYLON.Observable();
  19197. /**
  19198. * An event triggered before rendering the scene (right after animations and physics)
  19199. * @type {BABYLON.Observable}
  19200. */
  19201. this.onBeforeRenderObservable = new BABYLON.Observable();
  19202. /**
  19203. * An event triggered after rendering the scene
  19204. * @type {BABYLON.Observable}
  19205. */
  19206. this.onAfterRenderObservable = new BABYLON.Observable();
  19207. /**
  19208. * An event triggered before animating the scene
  19209. * @type {BABYLON.Observable}
  19210. */
  19211. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19212. /**
  19213. * An event triggered after animations processing
  19214. * @type {BABYLON.Observable}
  19215. */
  19216. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19217. /**
  19218. * An event triggered before draw calls are ready to be sent
  19219. * @type {BABYLON.Observable}
  19220. */
  19221. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19222. /**
  19223. * An event triggered after draw calls have been sent
  19224. * @type {BABYLON.Observable}
  19225. */
  19226. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19227. /**
  19228. * An event triggered when physic simulation is about to be run
  19229. * @type {BABYLON.Observable}
  19230. */
  19231. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19232. /**
  19233. * An event triggered when physic simulation has been done
  19234. * @type {BABYLON.Observable}
  19235. */
  19236. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19237. /**
  19238. * An event triggered when the scene is ready
  19239. * @type {BABYLON.Observable}
  19240. */
  19241. this.onReadyObservable = new BABYLON.Observable();
  19242. /**
  19243. * An event triggered before rendering a camera
  19244. * @type {BABYLON.Observable}
  19245. */
  19246. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19247. /**
  19248. * An event triggered after rendering a camera
  19249. * @type {BABYLON.Observable}
  19250. */
  19251. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19252. /**
  19253. * An event triggered when active meshes evaluation is about to start
  19254. * @type {BABYLON.Observable}
  19255. */
  19256. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19257. /**
  19258. * An event triggered when active meshes evaluation is done
  19259. * @type {BABYLON.Observable}
  19260. */
  19261. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19262. /**
  19263. * An event triggered when particles rendering is about to start
  19264. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19265. * @type {BABYLON.Observable}
  19266. */
  19267. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19268. /**
  19269. * An event triggered when particles rendering is done
  19270. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19271. * @type {BABYLON.Observable}
  19272. */
  19273. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered when sprites rendering is about to start
  19276. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19277. * @type {BABYLON.Observable}
  19278. */
  19279. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19280. /**
  19281. * An event triggered when sprites rendering is done
  19282. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19283. * @type {BABYLON.Observable}
  19284. */
  19285. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19286. /**
  19287. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19288. * @type {BABYLON.Observable}
  19289. */
  19290. this.onDataLoadedObservable = new BABYLON.Observable();
  19291. /**
  19292. * An event triggered when a camera is created
  19293. * @type {BABYLON.Observable}
  19294. */
  19295. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19296. /**
  19297. * An event triggered when a camera is removed
  19298. * @type {BABYLON.Observable}
  19299. */
  19300. this.onCameraRemovedObservable = new BABYLON.Observable();
  19301. /**
  19302. * An event triggered when a light is created
  19303. * @type {BABYLON.Observable}
  19304. */
  19305. this.onNewLightAddedObservable = new BABYLON.Observable();
  19306. /**
  19307. * An event triggered when a light is removed
  19308. * @type {BABYLON.Observable}
  19309. */
  19310. this.onLightRemovedObservable = new BABYLON.Observable();
  19311. /**
  19312. * An event triggered when a geometry is created
  19313. * @type {BABYLON.Observable}
  19314. */
  19315. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19316. /**
  19317. * An event triggered when a geometry is removed
  19318. * @type {BABYLON.Observable}
  19319. */
  19320. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19321. /**
  19322. * An event triggered when a transform node is created
  19323. * @type {BABYLON.Observable}
  19324. */
  19325. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19326. /**
  19327. * An event triggered when a transform node is removed
  19328. * @type {BABYLON.Observable}
  19329. */
  19330. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19331. /**
  19332. * An event triggered when a mesh is created
  19333. * @type {BABYLON.Observable}
  19334. */
  19335. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19336. /**
  19337. * An event triggered when a mesh is removed
  19338. * @type {BABYLON.Observable}
  19339. */
  19340. this.onMeshRemovedObservable = new BABYLON.Observable();
  19341. /**
  19342. * An event triggered when render targets are about to be rendered
  19343. * Can happen multiple times per frame.
  19344. * @type {BABYLON.Observable}
  19345. */
  19346. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19347. /**
  19348. * An event triggered when render targets were rendered.
  19349. * Can happen multiple times per frame.
  19350. * @type {BABYLON.Observable}
  19351. */
  19352. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19353. /**
  19354. * An event triggered before calculating deterministic simulation step
  19355. * @type {BABYLON.Observable}
  19356. */
  19357. this.onBeforeStepObservable = new BABYLON.Observable();
  19358. /**
  19359. * An event triggered after calculating deterministic simulation step
  19360. * @type {BABYLON.Observable}
  19361. */
  19362. this.onAfterStepObservable = new BABYLON.Observable();
  19363. /**
  19364. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19365. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19366. * 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)
  19367. */
  19368. this.onRenderingGroupObservable = new BABYLON.Observable();
  19369. // Animations
  19370. this.animations = [];
  19371. /**
  19372. * 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).
  19373. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19374. */
  19375. this.onPrePointerObservable = new BABYLON.Observable();
  19376. /**
  19377. * Observable event triggered each time an input event is received from the rendering canvas
  19378. */
  19379. this.onPointerObservable = new BABYLON.Observable();
  19380. this._meshPickProceed = false;
  19381. this._currentPickResult = null;
  19382. this._previousPickResult = null;
  19383. this._totalPointersPressed = 0;
  19384. this._doubleClickOccured = false;
  19385. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19386. this.cameraToUseForPointers = null;
  19387. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19388. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19389. this._startingPointerTime = 0;
  19390. this._previousStartingPointerTime = 0;
  19391. // Deterministic lockstep
  19392. this._timeAccumulator = 0;
  19393. this._currentStepId = 0;
  19394. this._currentInternalStep = 0;
  19395. // Keyboard
  19396. /**
  19397. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19398. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19399. */
  19400. this.onPreKeyboardObservable = new BABYLON.Observable();
  19401. /**
  19402. * Observable event triggered each time an keyboard event is received from the hosting window
  19403. */
  19404. this.onKeyboardObservable = new BABYLON.Observable();
  19405. // Coordinate system
  19406. /**
  19407. * use right-handed coordinate system on this scene.
  19408. * @type {boolean}
  19409. */
  19410. this._useRightHandedSystem = false;
  19411. // Fog
  19412. this._fogEnabled = true;
  19413. this._fogMode = Scene.FOGMODE_NONE;
  19414. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19415. this.fogDensity = 0.1;
  19416. this.fogStart = 0;
  19417. this.fogEnd = 1000.0;
  19418. // Lights
  19419. /**
  19420. * is shadow enabled on this scene.
  19421. * @type {boolean}
  19422. */
  19423. this._shadowsEnabled = true;
  19424. /**
  19425. * is light enabled on this scene.
  19426. * @type {boolean}
  19427. */
  19428. this._lightsEnabled = true;
  19429. /**
  19430. * All of the lights added to this scene.
  19431. * @see BABYLON.Light
  19432. * @type {BABYLON.Light[]}
  19433. */
  19434. this.lights = new Array();
  19435. // Cameras
  19436. /** All of the cameras added to this scene. */
  19437. this.cameras = new Array();
  19438. /** All of the active cameras added to this scene. */
  19439. this.activeCameras = new Array();
  19440. // Meshes
  19441. /**
  19442. * All of the tranform nodes added to this scene.
  19443. * @see BABYLON.TransformNode
  19444. * @type {BABYLON.TransformNode[]}
  19445. */
  19446. this.transformNodes = new Array();
  19447. /**
  19448. * All of the (abstract) meshes added to this scene.
  19449. * @see BABYLON.AbstractMesh
  19450. * @type {BABYLON.AbstractMesh[]}
  19451. */
  19452. this.meshes = new Array();
  19453. /**
  19454. * All of the animation groups added to this scene.
  19455. * @see BABYLON.AnimationGroup
  19456. * @type {BABYLON.AnimationGroup[]}
  19457. */
  19458. this.animationGroups = new Array();
  19459. // Geometries
  19460. this._geometries = new Array();
  19461. this.materials = new Array();
  19462. this.multiMaterials = new Array();
  19463. // Textures
  19464. this._texturesEnabled = true;
  19465. this.textures = new Array();
  19466. // Particles
  19467. this.particlesEnabled = true;
  19468. this.particleSystems = new Array();
  19469. // Sprites
  19470. this.spritesEnabled = true;
  19471. this.spriteManagers = new Array();
  19472. // Layers
  19473. this.layers = new Array();
  19474. this.highlightLayers = new Array();
  19475. // Skeletons
  19476. this._skeletonsEnabled = true;
  19477. this.skeletons = new Array();
  19478. // Morph targets
  19479. this.morphTargetManagers = new Array();
  19480. // Lens flares
  19481. this.lensFlaresEnabled = true;
  19482. this.lensFlareSystems = new Array();
  19483. // Collisions
  19484. this.collisionsEnabled = true;
  19485. /** Defines the gravity applied to this scene */
  19486. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19487. // Postprocesses
  19488. this.postProcesses = new Array();
  19489. this.postProcessesEnabled = true;
  19490. // Customs render targets
  19491. this.renderTargetsEnabled = true;
  19492. this.dumpNextRenderTargets = false;
  19493. this.customRenderTargets = new Array();
  19494. // Imported meshes
  19495. this.importedMeshesFiles = new Array();
  19496. // Probes
  19497. this.probesEnabled = true;
  19498. this.reflectionProbes = new Array();
  19499. this._actionManagers = new Array();
  19500. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19501. // Procedural textures
  19502. this.proceduralTexturesEnabled = true;
  19503. this._proceduralTextures = new Array();
  19504. this.soundTracks = new Array();
  19505. this._audioEnabled = true;
  19506. this._headphone = false;
  19507. // Performance counters
  19508. this._totalVertices = new BABYLON.PerfCounter();
  19509. this._activeIndices = new BABYLON.PerfCounter();
  19510. this._activeParticles = new BABYLON.PerfCounter();
  19511. this._activeBones = new BABYLON.PerfCounter();
  19512. this._animationTime = 0;
  19513. this.animationTimeScale = 1;
  19514. this._renderId = 0;
  19515. this._executeWhenReadyTimeoutId = -1;
  19516. this._intermediateRendering = false;
  19517. this._viewUpdateFlag = -1;
  19518. this._projectionUpdateFlag = -1;
  19519. this._alternateViewUpdateFlag = -1;
  19520. this._alternateProjectionUpdateFlag = -1;
  19521. this._toBeDisposed = new BABYLON.SmartArray(256);
  19522. this._activeRequests = new Array();
  19523. this._pendingData = new Array();
  19524. this._isDisposed = false;
  19525. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19526. this._activeMeshes = new BABYLON.SmartArray(256);
  19527. this._processedMaterials = new BABYLON.SmartArray(256);
  19528. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19529. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19530. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19531. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19532. this._activeAnimatables = new Array();
  19533. this._transformMatrix = BABYLON.Matrix.Zero();
  19534. this._useAlternateCameraConfiguration = false;
  19535. this._alternateRendering = false;
  19536. this.requireLightSorting = false;
  19537. this._activeMeshesFrozen = false;
  19538. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19539. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19540. this._engine.scenes.push(this);
  19541. this._uid = null;
  19542. this._renderingManager = new BABYLON.RenderingManager(this);
  19543. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19544. if (BABYLON.OutlineRenderer) {
  19545. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19546. }
  19547. if (BABYLON.Tools.IsWindowObjectExist()) {
  19548. this.attachControl();
  19549. }
  19550. //simplification queue
  19551. if (BABYLON.SimplificationQueue) {
  19552. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19553. }
  19554. //collision coordinator initialization. For now legacy per default.
  19555. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19556. // Uniform Buffer
  19557. this._createUbo();
  19558. // Default Image processing definition.
  19559. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19560. }
  19561. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19562. /** The fog is deactivated */
  19563. get: function () {
  19564. return Scene._FOGMODE_NONE;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19570. /** The fog density is following an exponential function */
  19571. get: function () {
  19572. return Scene._FOGMODE_EXP;
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19578. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19579. get: function () {
  19580. return Scene._FOGMODE_EXP2;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19586. /** The fog density is following a linear function. */
  19587. get: function () {
  19588. return Scene._FOGMODE_LINEAR;
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19594. /**
  19595. * Texture used in all pbr material as the reflection texture.
  19596. * As in the majority of the scene they are the same (exception for multi room and so on),
  19597. * this is easier to reference from here than from all the materials.
  19598. */
  19599. get: function () {
  19600. return this._environmentTexture;
  19601. },
  19602. /**
  19603. * Texture used in all pbr material as the reflection texture.
  19604. * As in the majority of the scene they are the same (exception for multi room and so on),
  19605. * this is easier to set here than in all the materials.
  19606. */
  19607. set: function (value) {
  19608. if (this._environmentTexture === value) {
  19609. return;
  19610. }
  19611. this._environmentTexture = value;
  19612. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19613. },
  19614. enumerable: true,
  19615. configurable: true
  19616. });
  19617. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19618. /**
  19619. * Default image processing configuration used either in the rendering
  19620. * Forward main pass or through the imageProcessingPostProcess if present.
  19621. * As in the majority of the scene they are the same (exception for multi camera),
  19622. * this is easier to reference from here than from all the materials and post process.
  19623. *
  19624. * No setter as we it is a shared configuration, you can set the values instead.
  19625. */
  19626. get: function () {
  19627. return this._imageProcessingConfiguration;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19633. get: function () {
  19634. return this._forcePointsCloud;
  19635. },
  19636. set: function (value) {
  19637. if (this._forcePointsCloud === value) {
  19638. return;
  19639. }
  19640. this._forcePointsCloud = value;
  19641. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(Scene.prototype, "onDispose", {
  19647. /** A function to be executed when this scene is disposed. */
  19648. set: function (callback) {
  19649. if (this._onDisposeObserver) {
  19650. this.onDisposeObservable.remove(this._onDisposeObserver);
  19651. }
  19652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19653. },
  19654. enumerable: true,
  19655. configurable: true
  19656. });
  19657. Object.defineProperty(Scene.prototype, "beforeRender", {
  19658. /** A function to be executed before rendering this scene */
  19659. set: function (callback) {
  19660. if (this._onBeforeRenderObserver) {
  19661. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19662. }
  19663. if (callback) {
  19664. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19665. }
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(Scene.prototype, "afterRender", {
  19671. /** A function to be executed after rendering this scene */
  19672. set: function (callback) {
  19673. if (this._onAfterRenderObserver) {
  19674. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19675. }
  19676. if (callback) {
  19677. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19678. }
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19684. set: function (callback) {
  19685. if (this._onBeforeCameraRenderObserver) {
  19686. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19687. }
  19688. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19694. set: function (callback) {
  19695. if (this._onAfterCameraRenderObserver) {
  19696. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19697. }
  19698. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19704. get: function () {
  19705. if (!this._gamepadManager) {
  19706. this._gamepadManager = new BABYLON.GamepadManager(this);
  19707. }
  19708. return this._gamepadManager;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19714. get: function () {
  19715. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19721. get: function () {
  19722. return this._useRightHandedSystem;
  19723. },
  19724. set: function (value) {
  19725. if (this._useRightHandedSystem === value) {
  19726. return;
  19727. }
  19728. this._useRightHandedSystem = value;
  19729. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Scene.prototype.setStepId = function (newStepId) {
  19735. this._currentStepId = newStepId;
  19736. };
  19737. ;
  19738. Scene.prototype.getStepId = function () {
  19739. return this._currentStepId;
  19740. };
  19741. ;
  19742. Scene.prototype.getInternalStep = function () {
  19743. return this._currentInternalStep;
  19744. };
  19745. ;
  19746. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19747. get: function () {
  19748. return this._fogEnabled;
  19749. },
  19750. /**
  19751. * is fog enabled on this scene.
  19752. */
  19753. set: function (value) {
  19754. if (this._fogEnabled === value) {
  19755. return;
  19756. }
  19757. this._fogEnabled = value;
  19758. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Scene.prototype, "fogMode", {
  19764. get: function () {
  19765. return this._fogMode;
  19766. },
  19767. set: function (value) {
  19768. if (this._fogMode === value) {
  19769. return;
  19770. }
  19771. this._fogMode = value;
  19772. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19778. get: function () {
  19779. return this._shadowsEnabled;
  19780. },
  19781. set: function (value) {
  19782. if (this._shadowsEnabled === value) {
  19783. return;
  19784. }
  19785. this._shadowsEnabled = value;
  19786. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19792. get: function () {
  19793. return this._lightsEnabled;
  19794. },
  19795. set: function (value) {
  19796. if (this._lightsEnabled === value) {
  19797. return;
  19798. }
  19799. this._lightsEnabled = value;
  19800. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19806. /** The default material used on meshes when no material is affected */
  19807. get: function () {
  19808. if (!this._defaultMaterial) {
  19809. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19810. }
  19811. return this._defaultMaterial;
  19812. },
  19813. /** The default material used on meshes when no material is affected */
  19814. set: function (value) {
  19815. this._defaultMaterial = value;
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19821. get: function () {
  19822. return this._texturesEnabled;
  19823. },
  19824. set: function (value) {
  19825. if (this._texturesEnabled === value) {
  19826. return;
  19827. }
  19828. this._texturesEnabled = value;
  19829. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19835. get: function () {
  19836. return this._skeletonsEnabled;
  19837. },
  19838. set: function (value) {
  19839. if (this._skeletonsEnabled === value) {
  19840. return;
  19841. }
  19842. this._skeletonsEnabled = value;
  19843. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19849. get: function () {
  19850. if (!this._postProcessRenderPipelineManager) {
  19851. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19852. }
  19853. return this._postProcessRenderPipelineManager;
  19854. },
  19855. enumerable: true,
  19856. configurable: true
  19857. });
  19858. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19859. get: function () {
  19860. if (!this._mainSoundTrack) {
  19861. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19862. }
  19863. return this._mainSoundTrack;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19869. get: function () {
  19870. return this._alternateRendering;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19876. get: function () {
  19877. return this._frustumPlanes;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(Scene.prototype, "debugLayer", {
  19883. // Properties
  19884. get: function () {
  19885. if (!this._debugLayer) {
  19886. this._debugLayer = new BABYLON.DebugLayer(this);
  19887. }
  19888. return this._debugLayer;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19894. get: function () {
  19895. return this._workerCollisions;
  19896. },
  19897. set: function (enabled) {
  19898. if (!BABYLON.CollisionCoordinatorLegacy) {
  19899. return;
  19900. }
  19901. enabled = (enabled && !!Worker);
  19902. this._workerCollisions = enabled;
  19903. if (this.collisionCoordinator) {
  19904. this.collisionCoordinator.destroy();
  19905. }
  19906. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19907. this.collisionCoordinator.init(this);
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19913. get: function () {
  19914. return this._selectionOctree;
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19920. /**
  19921. * The mesh that is currently under the pointer.
  19922. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19923. */
  19924. get: function () {
  19925. return this._pointerOverMesh;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(Scene.prototype, "pointerX", {
  19931. /**
  19932. * Current on-screen X position of the pointer
  19933. * @return {number} X position of the pointer
  19934. */
  19935. get: function () {
  19936. return this._pointerX;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Scene.prototype, "pointerY", {
  19942. /**
  19943. * Current on-screen Y position of the pointer
  19944. * @return {number} Y position of the pointer
  19945. */
  19946. get: function () {
  19947. return this._pointerY;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Scene.prototype.getCachedMaterial = function () {
  19953. return this._cachedMaterial;
  19954. };
  19955. Scene.prototype.getCachedEffect = function () {
  19956. return this._cachedEffect;
  19957. };
  19958. Scene.prototype.getCachedVisibility = function () {
  19959. return this._cachedVisibility;
  19960. };
  19961. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19962. if (visibility === void 0) { visibility = 1; }
  19963. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19964. };
  19965. Scene.prototype.getBoundingBoxRenderer = function () {
  19966. if (!this._boundingBoxRenderer) {
  19967. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19968. }
  19969. return this._boundingBoxRenderer;
  19970. };
  19971. Scene.prototype.getOutlineRenderer = function () {
  19972. return this._outlineRenderer;
  19973. };
  19974. Scene.prototype.getEngine = function () {
  19975. return this._engine;
  19976. };
  19977. Scene.prototype.getTotalVertices = function () {
  19978. return this._totalVertices.current;
  19979. };
  19980. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19981. get: function () {
  19982. return this._totalVertices;
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. Scene.prototype.getActiveIndices = function () {
  19988. return this._activeIndices.current;
  19989. };
  19990. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19991. get: function () {
  19992. return this._activeIndices;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Scene.prototype.getActiveParticles = function () {
  19998. return this._activeParticles.current;
  19999. };
  20000. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20001. get: function () {
  20002. return this._activeParticles;
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. Scene.prototype.getActiveBones = function () {
  20008. return this._activeBones.current;
  20009. };
  20010. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20011. get: function () {
  20012. return this._activeBones;
  20013. },
  20014. enumerable: true,
  20015. configurable: true
  20016. });
  20017. // Stats
  20018. Scene.prototype.getInterFramePerfCounter = function () {
  20019. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20020. return 0;
  20021. };
  20022. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20023. get: function () {
  20024. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20025. return null;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Scene.prototype.getLastFrameDuration = function () {
  20031. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20032. return 0;
  20033. };
  20034. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20035. get: function () {
  20036. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20037. return null;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20043. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20044. return 0;
  20045. };
  20046. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20047. get: function () {
  20048. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20049. return null;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Scene.prototype.getActiveMeshes = function () {
  20055. return this._activeMeshes;
  20056. };
  20057. Scene.prototype.getRenderTargetsDuration = function () {
  20058. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20059. return 0;
  20060. };
  20061. Scene.prototype.getRenderDuration = function () {
  20062. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20063. return 0;
  20064. };
  20065. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20066. get: function () {
  20067. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20068. return null;
  20069. },
  20070. enumerable: true,
  20071. configurable: true
  20072. });
  20073. Scene.prototype.getParticlesDuration = function () {
  20074. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20075. return 0;
  20076. };
  20077. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20078. get: function () {
  20079. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20080. return null;
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. Scene.prototype.getSpritesDuration = function () {
  20086. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20087. return 0;
  20088. };
  20089. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20090. get: function () {
  20091. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20092. return null;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Scene.prototype.getAnimationRatio = function () {
  20098. return this._animationRatio;
  20099. };
  20100. Scene.prototype.getRenderId = function () {
  20101. return this._renderId;
  20102. };
  20103. Scene.prototype.incrementRenderId = function () {
  20104. this._renderId++;
  20105. };
  20106. Scene.prototype._updatePointerPosition = function (evt) {
  20107. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20108. if (!canvasRect) {
  20109. return;
  20110. }
  20111. this._pointerX = evt.clientX - canvasRect.left;
  20112. this._pointerY = evt.clientY - canvasRect.top;
  20113. this._unTranslatedPointerX = this._pointerX;
  20114. this._unTranslatedPointerY = this._pointerY;
  20115. };
  20116. Scene.prototype._createUbo = function () {
  20117. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20118. this._sceneUbo.addUniform("viewProjection", 16);
  20119. this._sceneUbo.addUniform("view", 16);
  20120. };
  20121. Scene.prototype._createAlternateUbo = function () {
  20122. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20123. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20124. this._alternateSceneUbo.addUniform("view", 16);
  20125. };
  20126. // Pointers handling
  20127. /**
  20128. * Use this method to simulate a pointer move on a mesh
  20129. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20130. */
  20131. Scene.prototype.simulatePointerMove = function (pickResult) {
  20132. var evt = new PointerEvent("pointermove");
  20133. return this._processPointerMove(pickResult, evt);
  20134. };
  20135. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20136. var canvas = this._engine.getRenderingCanvas();
  20137. if (!canvas) {
  20138. return this;
  20139. }
  20140. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20141. this.setPointerOverSprite(null);
  20142. this.setPointerOverMesh(pickResult.pickedMesh);
  20143. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20144. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20145. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20146. }
  20147. else {
  20148. canvas.style.cursor = this.hoverCursor;
  20149. }
  20150. }
  20151. else {
  20152. canvas.style.cursor = this.defaultCursor;
  20153. }
  20154. }
  20155. else {
  20156. this.setPointerOverMesh(null);
  20157. // Sprites
  20158. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20159. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20160. this.setPointerOverSprite(pickResult.pickedSprite);
  20161. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20162. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20163. }
  20164. else {
  20165. canvas.style.cursor = this.hoverCursor;
  20166. }
  20167. }
  20168. else {
  20169. this.setPointerOverSprite(null);
  20170. // Restore pointer
  20171. canvas.style.cursor = this.defaultCursor;
  20172. }
  20173. }
  20174. if (pickResult) {
  20175. if (this.onPointerMove) {
  20176. this.onPointerMove(evt, pickResult);
  20177. }
  20178. if (this.onPointerObservable.hasObservers()) {
  20179. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20180. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20181. this.onPointerObservable.notifyObservers(pi, type);
  20182. }
  20183. }
  20184. return this;
  20185. };
  20186. /**
  20187. * Use this method to simulate a pointer down on a mesh
  20188. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20189. */
  20190. Scene.prototype.simulatePointerDown = function (pickResult) {
  20191. var evt = new PointerEvent("pointerdown");
  20192. return this._processPointerDown(pickResult, evt);
  20193. };
  20194. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20195. var _this = this;
  20196. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20197. this._pickedDownMesh = pickResult.pickedMesh;
  20198. var actionManager = pickResult.pickedMesh.actionManager;
  20199. if (actionManager) {
  20200. if (actionManager.hasPickTriggers) {
  20201. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20202. switch (evt.button) {
  20203. case 0:
  20204. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20205. break;
  20206. case 1:
  20207. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20208. break;
  20209. case 2:
  20210. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20211. break;
  20212. }
  20213. }
  20214. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20215. window.setTimeout(function () {
  20216. 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);
  20217. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20218. if (_this._totalPointersPressed !== 0 &&
  20219. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20220. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20221. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20222. _this._startingPointerTime = 0;
  20223. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20224. }
  20225. }
  20226. }, Scene.LongPressDelay);
  20227. }
  20228. }
  20229. }
  20230. if (pickResult) {
  20231. if (this.onPointerDown) {
  20232. this.onPointerDown(evt, pickResult);
  20233. }
  20234. if (this.onPointerObservable.hasObservers()) {
  20235. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20236. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20237. this.onPointerObservable.notifyObservers(pi, type);
  20238. }
  20239. }
  20240. return this;
  20241. };
  20242. /**
  20243. * Use this method to simulate a pointer up on a mesh
  20244. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20245. */
  20246. Scene.prototype.simulatePointerUp = function (pickResult) {
  20247. var evt = new PointerEvent("pointerup");
  20248. var clickInfo = new ClickInfo();
  20249. clickInfo.singleClick = true;
  20250. clickInfo.ignore = true;
  20251. return this._processPointerUp(pickResult, evt, clickInfo);
  20252. };
  20253. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20254. if (pickResult && pickResult && pickResult.pickedMesh) {
  20255. this._pickedUpMesh = pickResult.pickedMesh;
  20256. if (this._pickedDownMesh === this._pickedUpMesh) {
  20257. if (this.onPointerPick) {
  20258. this.onPointerPick(evt, pickResult);
  20259. }
  20260. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20261. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20263. this.onPointerObservable.notifyObservers(pi, type);
  20264. }
  20265. }
  20266. if (pickResult.pickedMesh.actionManager) {
  20267. if (clickInfo.ignore) {
  20268. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20269. }
  20270. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20271. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20272. }
  20273. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20274. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20275. }
  20276. }
  20277. }
  20278. if (this._pickedDownMesh &&
  20279. this._pickedDownMesh.actionManager &&
  20280. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20281. this._pickedDownMesh !== this._pickedUpMesh) {
  20282. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20283. }
  20284. if (this.onPointerUp) {
  20285. this.onPointerUp(evt, pickResult);
  20286. }
  20287. if (this.onPointerObservable.hasObservers()) {
  20288. if (!clickInfo.ignore) {
  20289. if (!clickInfo.hasSwiped) {
  20290. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20291. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20292. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20293. this.onPointerObservable.notifyObservers(pi, type);
  20294. }
  20295. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20296. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20297. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20298. this.onPointerObservable.notifyObservers(pi, type);
  20299. }
  20300. }
  20301. }
  20302. else {
  20303. var type = BABYLON.PointerEventTypes.POINTERUP;
  20304. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20305. this.onPointerObservable.notifyObservers(pi, type);
  20306. }
  20307. }
  20308. return this;
  20309. };
  20310. /**
  20311. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20312. * @param attachUp defines if you want to attach events to pointerup
  20313. * @param attachDown defines if you want to attach events to pointerdown
  20314. * @param attachMove defines if you want to attach events to pointermove
  20315. */
  20316. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20317. var _this = this;
  20318. if (attachUp === void 0) { attachUp = true; }
  20319. if (attachDown === void 0) { attachDown = true; }
  20320. if (attachMove === void 0) { attachMove = true; }
  20321. this._initActionManager = function (act, clickInfo) {
  20322. if (!_this._meshPickProceed) {
  20323. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20324. _this._currentPickResult = pickResult;
  20325. if (pickResult) {
  20326. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20327. }
  20328. _this._meshPickProceed = true;
  20329. }
  20330. return act;
  20331. };
  20332. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20333. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20334. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20335. btn !== _this._previousButtonPressed) {
  20336. _this._doubleClickOccured = false;
  20337. clickInfo.singleClick = true;
  20338. clickInfo.ignore = false;
  20339. cb(clickInfo, _this._currentPickResult);
  20340. }
  20341. };
  20342. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20343. var clickInfo = new ClickInfo();
  20344. _this._currentPickResult = null;
  20345. var act = null;
  20346. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20347. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20348. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20349. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20350. act = _this._initActionManager(act, clickInfo);
  20351. if (act)
  20352. checkPicking = act.hasPickTriggers;
  20353. }
  20354. if (checkPicking) {
  20355. var btn = evt.button;
  20356. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20357. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20358. if (!clickInfo.hasSwiped) {
  20359. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20360. if (!checkSingleClickImmediately) {
  20361. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20362. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20363. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20364. act = _this._initActionManager(act, clickInfo);
  20365. if (act)
  20366. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20367. }
  20368. }
  20369. if (checkSingleClickImmediately) {
  20370. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20371. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20372. btn !== _this._previousButtonPressed) {
  20373. clickInfo.singleClick = true;
  20374. cb(clickInfo, _this._currentPickResult);
  20375. }
  20376. }
  20377. else {
  20378. // wait that no double click has been raised during the double click delay
  20379. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20380. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20381. }
  20382. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20383. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20384. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20385. act = _this._initActionManager(act, clickInfo);
  20386. if (act)
  20387. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20388. }
  20389. if (checkDoubleClick) {
  20390. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20391. if (btn === _this._previousButtonPressed &&
  20392. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20393. !_this._doubleClickOccured) {
  20394. // pointer has not moved for 2 clicks, it's a double click
  20395. if (!clickInfo.hasSwiped &&
  20396. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20397. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20398. _this._previousStartingPointerTime = 0;
  20399. _this._doubleClickOccured = true;
  20400. clickInfo.doubleClick = true;
  20401. clickInfo.ignore = false;
  20402. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20403. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20404. }
  20405. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20406. cb(clickInfo, _this._currentPickResult);
  20407. }
  20408. else {
  20409. _this._doubleClickOccured = false;
  20410. _this._previousStartingPointerTime = _this._startingPointerTime;
  20411. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20412. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20413. _this._previousButtonPressed = btn;
  20414. if (Scene.ExclusiveDoubleClickMode) {
  20415. if (_this._previousDelayedSimpleClickTimeout) {
  20416. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20417. }
  20418. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20419. cb(clickInfo, _this._previousPickResult);
  20420. }
  20421. else {
  20422. cb(clickInfo, _this._currentPickResult);
  20423. }
  20424. }
  20425. }
  20426. else {
  20427. _this._doubleClickOccured = false;
  20428. _this._previousStartingPointerTime = _this._startingPointerTime;
  20429. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20430. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20431. _this._previousButtonPressed = btn;
  20432. }
  20433. }
  20434. }
  20435. }
  20436. clickInfo.ignore = true;
  20437. cb(clickInfo, _this._currentPickResult);
  20438. };
  20439. this._spritePredicate = function (sprite) {
  20440. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20441. };
  20442. this._onPointerMove = function (evt) {
  20443. _this._updatePointerPosition(evt);
  20444. // PreObservable support
  20445. if (_this.onPrePointerObservable.hasObservers()) {
  20446. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20447. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20448. _this.onPrePointerObservable.notifyObservers(pi, type);
  20449. if (pi.skipOnPointerObservable) {
  20450. return;
  20451. }
  20452. }
  20453. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20454. return;
  20455. }
  20456. if (!_this.pointerMovePredicate) {
  20457. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20458. }
  20459. // Meshes
  20460. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20461. _this._processPointerMove(pickResult, evt);
  20462. };
  20463. this._onPointerDown = function (evt) {
  20464. _this._totalPointersPressed++;
  20465. _this._pickedDownMesh = null;
  20466. _this._meshPickProceed = false;
  20467. _this._updatePointerPosition(evt);
  20468. if (_this.preventDefaultOnPointerDown && canvas) {
  20469. evt.preventDefault();
  20470. canvas.focus();
  20471. }
  20472. // PreObservable support
  20473. if (_this.onPrePointerObservable.hasObservers()) {
  20474. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20475. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20476. _this.onPrePointerObservable.notifyObservers(pi, type);
  20477. if (pi.skipOnPointerObservable) {
  20478. return;
  20479. }
  20480. }
  20481. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20482. return;
  20483. }
  20484. _this._startingPointerPosition.x = _this._pointerX;
  20485. _this._startingPointerPosition.y = _this._pointerY;
  20486. _this._startingPointerTime = new Date().getTime();
  20487. if (!_this.pointerDownPredicate) {
  20488. _this.pointerDownPredicate = function (mesh) {
  20489. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20490. };
  20491. }
  20492. // Meshes
  20493. _this._pickedDownMesh = null;
  20494. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20495. _this._processPointerDown(pickResult, evt);
  20496. // Sprites
  20497. _this._pickedDownSprite = null;
  20498. if (_this.spriteManagers.length > 0) {
  20499. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20500. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20501. if (pickResult.pickedSprite.actionManager) {
  20502. _this._pickedDownSprite = pickResult.pickedSprite;
  20503. switch (evt.button) {
  20504. case 0:
  20505. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20506. break;
  20507. case 1:
  20508. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20509. break;
  20510. case 2:
  20511. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20512. break;
  20513. }
  20514. if (pickResult.pickedSprite.actionManager) {
  20515. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20516. }
  20517. }
  20518. }
  20519. }
  20520. };
  20521. this._onPointerUp = function (evt) {
  20522. if (_this._totalPointersPressed === 0) {
  20523. return; // So we need to test it the pointer down was pressed before.
  20524. }
  20525. _this._totalPointersPressed--;
  20526. _this._pickedUpMesh = null;
  20527. _this._meshPickProceed = false;
  20528. _this._updatePointerPosition(evt);
  20529. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20530. // PreObservable support
  20531. if (_this.onPrePointerObservable.hasObservers()) {
  20532. if (!clickInfo.ignore) {
  20533. if (!clickInfo.hasSwiped) {
  20534. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20535. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20536. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20537. _this.onPrePointerObservable.notifyObservers(pi, type);
  20538. if (pi.skipOnPointerObservable) {
  20539. return;
  20540. }
  20541. }
  20542. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20543. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20544. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20545. _this.onPrePointerObservable.notifyObservers(pi, type);
  20546. if (pi.skipOnPointerObservable) {
  20547. return;
  20548. }
  20549. }
  20550. }
  20551. }
  20552. else {
  20553. var type = BABYLON.PointerEventTypes.POINTERUP;
  20554. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20555. _this.onPrePointerObservable.notifyObservers(pi, type);
  20556. if (pi.skipOnPointerObservable) {
  20557. return;
  20558. }
  20559. }
  20560. }
  20561. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20562. return;
  20563. }
  20564. if (!_this.pointerUpPredicate) {
  20565. _this.pointerUpPredicate = function (mesh) {
  20566. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20567. };
  20568. }
  20569. // Meshes
  20570. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20571. _this._initActionManager(null, clickInfo);
  20572. }
  20573. if (!pickResult) {
  20574. pickResult = _this._currentPickResult;
  20575. }
  20576. _this._processPointerUp(pickResult, evt, clickInfo);
  20577. // Sprites
  20578. if (_this.spriteManagers.length > 0) {
  20579. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20580. if (spritePickResult) {
  20581. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20582. if (spritePickResult.pickedSprite.actionManager) {
  20583. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20584. if (spritePickResult.pickedSprite.actionManager) {
  20585. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20586. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20587. }
  20588. }
  20589. }
  20590. }
  20591. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20592. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20593. }
  20594. }
  20595. }
  20596. _this._previousPickResult = _this._currentPickResult;
  20597. });
  20598. };
  20599. this._onKeyDown = function (evt) {
  20600. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20601. if (_this.onPreKeyboardObservable.hasObservers()) {
  20602. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20603. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20604. if (pi.skipOnPointerObservable) {
  20605. return;
  20606. }
  20607. }
  20608. if (_this.onKeyboardObservable.hasObservers()) {
  20609. var pi = new BABYLON.KeyboardInfo(type, evt);
  20610. _this.onKeyboardObservable.notifyObservers(pi, type);
  20611. }
  20612. if (_this.actionManager) {
  20613. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20614. }
  20615. };
  20616. this._onKeyUp = function (evt) {
  20617. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20618. if (_this.onPreKeyboardObservable.hasObservers()) {
  20619. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20620. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20621. if (pi.skipOnPointerObservable) {
  20622. return;
  20623. }
  20624. }
  20625. if (_this.onKeyboardObservable.hasObservers()) {
  20626. var pi = new BABYLON.KeyboardInfo(type, evt);
  20627. _this.onKeyboardObservable.notifyObservers(pi, type);
  20628. }
  20629. if (_this.actionManager) {
  20630. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20631. }
  20632. };
  20633. var engine = this.getEngine();
  20634. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20635. if (!canvas) {
  20636. return;
  20637. }
  20638. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20639. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20640. });
  20641. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20642. if (!canvas) {
  20643. return;
  20644. }
  20645. canvas.removeEventListener("keydown", _this._onKeyDown);
  20646. canvas.removeEventListener("keyup", _this._onKeyUp);
  20647. });
  20648. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20649. var canvas = this._engine.getRenderingCanvas();
  20650. if (!canvas) {
  20651. return;
  20652. }
  20653. if (attachMove) {
  20654. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20655. // Wheel
  20656. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20657. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20658. }
  20659. if (attachDown) {
  20660. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20661. }
  20662. if (attachUp) {
  20663. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20664. }
  20665. canvas.tabIndex = 1;
  20666. };
  20667. Scene.prototype.detachControl = function () {
  20668. var engine = this.getEngine();
  20669. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20670. var canvas = engine.getRenderingCanvas();
  20671. if (!canvas) {
  20672. return;
  20673. }
  20674. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20675. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20676. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20677. if (this._onCanvasBlurObserver) {
  20678. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20679. }
  20680. if (this._onCanvasFocusObserver) {
  20681. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20682. }
  20683. // Wheel
  20684. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20685. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20686. // Keyboard
  20687. canvas.removeEventListener("keydown", this._onKeyDown);
  20688. canvas.removeEventListener("keyup", this._onKeyUp);
  20689. // Observables
  20690. this.onKeyboardObservable.clear();
  20691. this.onPreKeyboardObservable.clear();
  20692. this.onPointerObservable.clear();
  20693. this.onPrePointerObservable.clear();
  20694. };
  20695. /**
  20696. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20697. * Delay loaded resources are not taking in account
  20698. * @return true if all required resources are ready
  20699. */
  20700. Scene.prototype.isReady = function () {
  20701. if (this._isDisposed) {
  20702. return false;
  20703. }
  20704. if (this._pendingData.length > 0) {
  20705. return false;
  20706. }
  20707. var index;
  20708. var engine = this.getEngine();
  20709. // Geometries
  20710. for (index = 0; index < this._geometries.length; index++) {
  20711. var geometry = this._geometries[index];
  20712. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20713. return false;
  20714. }
  20715. }
  20716. // Meshes
  20717. for (index = 0; index < this.meshes.length; index++) {
  20718. var mesh = this.meshes[index];
  20719. if (!mesh.isEnabled()) {
  20720. continue;
  20721. }
  20722. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20723. continue;
  20724. }
  20725. if (!mesh.isReady()) {
  20726. return false;
  20727. }
  20728. // Highlight layers
  20729. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20730. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20731. var layer = _a[_i];
  20732. if (!layer.hasMesh(mesh)) {
  20733. continue;
  20734. }
  20735. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20736. var subMesh = _c[_b];
  20737. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20738. return false;
  20739. }
  20740. }
  20741. }
  20742. }
  20743. return true;
  20744. };
  20745. Scene.prototype.resetCachedMaterial = function () {
  20746. this._cachedMaterial = null;
  20747. this._cachedEffect = null;
  20748. this._cachedVisibility = null;
  20749. };
  20750. Scene.prototype.registerBeforeRender = function (func) {
  20751. this.onBeforeRenderObservable.add(func);
  20752. };
  20753. Scene.prototype.unregisterBeforeRender = function (func) {
  20754. this.onBeforeRenderObservable.removeCallback(func);
  20755. };
  20756. Scene.prototype.registerAfterRender = function (func) {
  20757. this.onAfterRenderObservable.add(func);
  20758. };
  20759. Scene.prototype.unregisterAfterRender = function (func) {
  20760. this.onAfterRenderObservable.removeCallback(func);
  20761. };
  20762. Scene.prototype._executeOnceBeforeRender = function (func) {
  20763. var _this = this;
  20764. var execFunc = function () {
  20765. func();
  20766. setTimeout(function () {
  20767. _this.unregisterBeforeRender(execFunc);
  20768. });
  20769. };
  20770. this.registerBeforeRender(execFunc);
  20771. };
  20772. /**
  20773. * The provided function will run before render once and will be disposed afterwards.
  20774. * A timeout delay can be provided so that the function will be executed in N ms.
  20775. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20776. * @param func The function to be executed.
  20777. * @param timeout optional delay in ms
  20778. */
  20779. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20780. var _this = this;
  20781. if (timeout !== undefined) {
  20782. setTimeout(function () {
  20783. _this._executeOnceBeforeRender(func);
  20784. }, timeout);
  20785. }
  20786. else {
  20787. this._executeOnceBeforeRender(func);
  20788. }
  20789. };
  20790. Scene.prototype._addPendingData = function (data) {
  20791. this._pendingData.push(data);
  20792. };
  20793. Scene.prototype._removePendingData = function (data) {
  20794. var wasLoading = this.isLoading;
  20795. var index = this._pendingData.indexOf(data);
  20796. if (index !== -1) {
  20797. this._pendingData.splice(index, 1);
  20798. }
  20799. if (wasLoading && !this.isLoading) {
  20800. this.onDataLoadedObservable.notifyObservers(this);
  20801. }
  20802. };
  20803. Scene.prototype.getWaitingItemsCount = function () {
  20804. return this._pendingData.length;
  20805. };
  20806. Object.defineProperty(Scene.prototype, "isLoading", {
  20807. get: function () {
  20808. return this._pendingData.length > 0;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. /**
  20814. * Registers a function to be executed when the scene is ready.
  20815. * @param {Function} func - the function to be executed.
  20816. */
  20817. Scene.prototype.executeWhenReady = function (func) {
  20818. var _this = this;
  20819. this.onReadyObservable.add(func);
  20820. if (this._executeWhenReadyTimeoutId !== -1) {
  20821. return;
  20822. }
  20823. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20824. _this._checkIsReady();
  20825. }, 150);
  20826. };
  20827. Scene.prototype._checkIsReady = function () {
  20828. var _this = this;
  20829. if (this.isReady()) {
  20830. this.onReadyObservable.notifyObservers(this);
  20831. this.onReadyObservable.clear();
  20832. this._executeWhenReadyTimeoutId = -1;
  20833. return;
  20834. }
  20835. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20836. _this._checkIsReady();
  20837. }, 150);
  20838. };
  20839. // Animations
  20840. /**
  20841. * Will start the animation sequence of a given target
  20842. * @param target - the target
  20843. * @param {number} from - from which frame should animation start
  20844. * @param {number} to - till which frame should animation run.
  20845. * @param {boolean} [loop] - should the animation loop
  20846. * @param {number} [speedRatio] - the speed in which to run the animation
  20847. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20848. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20849. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20850. * See BABYLON.Animatable
  20851. */
  20852. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20853. if (speedRatio === void 0) { speedRatio = 1.0; }
  20854. if (from > to && speedRatio > 0) {
  20855. speedRatio *= -1;
  20856. }
  20857. this.stopAnimation(target);
  20858. if (!animatable) {
  20859. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20860. }
  20861. // Local animations
  20862. if (target.animations) {
  20863. animatable.appendAnimations(target, target.animations);
  20864. }
  20865. // Children animations
  20866. if (target.getAnimatables) {
  20867. var animatables = target.getAnimatables();
  20868. for (var index = 0; index < animatables.length; index++) {
  20869. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20870. }
  20871. }
  20872. animatable.reset();
  20873. return animatable;
  20874. };
  20875. /**
  20876. * Begin a new animation on a given node
  20877. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20878. * @param {BABYLON.Animation[]} defines the list of animations to start
  20879. * @param {number} from defines the initial value
  20880. * @param {number} to defines the final value
  20881. * @param {boolean} loop defines if you want animation to loop (off by default)
  20882. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20883. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20884. * @returns the list of created animatables
  20885. */
  20886. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20887. if (speedRatio === undefined) {
  20888. speedRatio = 1.0;
  20889. }
  20890. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20891. return animatable;
  20892. };
  20893. /**
  20894. * Begin a new animation on a given node and its hierarchy
  20895. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20896. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  20897. * @param {BABYLON.Animation[]} defines the list of animations to start
  20898. * @param {number} from defines the initial value
  20899. * @param {number} to defines the final value
  20900. * @param {boolean} loop defines if you want animation to loop (off by default)
  20901. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20902. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20903. * @returns the list of animatables created for all nodes
  20904. */
  20905. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20906. var children = target.getDescendants(directDescendantsOnly);
  20907. var result = [];
  20908. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20909. var child = children_1[_i];
  20910. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20911. }
  20912. return result;
  20913. };
  20914. Scene.prototype.getAnimatableByTarget = function (target) {
  20915. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20916. if (this._activeAnimatables[index].target === target) {
  20917. return this._activeAnimatables[index];
  20918. }
  20919. }
  20920. return null;
  20921. };
  20922. Object.defineProperty(Scene.prototype, "animatables", {
  20923. get: function () {
  20924. return this._activeAnimatables;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. /**
  20930. * Will stop the animation of the given target
  20931. * @param target - the target
  20932. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20933. * @see beginAnimation
  20934. */
  20935. Scene.prototype.stopAnimation = function (target, animationName) {
  20936. var animatable = this.getAnimatableByTarget(target);
  20937. if (animatable) {
  20938. animatable.stop(animationName);
  20939. }
  20940. };
  20941. /**
  20942. * Stops and removes all animations that have been applied to the scene
  20943. */
  20944. Scene.prototype.stopAllAnimations = function () {
  20945. if (this._activeAnimatables) {
  20946. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20947. this._activeAnimatables[i].stop();
  20948. }
  20949. this._activeAnimatables = [];
  20950. }
  20951. };
  20952. Scene.prototype._animate = function () {
  20953. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20954. return;
  20955. }
  20956. // Getting time
  20957. var now = BABYLON.Tools.Now;
  20958. if (!this._animationTimeLast) {
  20959. if (this._pendingData.length > 0) {
  20960. return;
  20961. }
  20962. this._animationTimeLast = now;
  20963. }
  20964. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20965. this._animationTime += deltaTime;
  20966. this._animationTimeLast = now;
  20967. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20968. this._activeAnimatables[index]._animate(this._animationTime);
  20969. }
  20970. };
  20971. // Matrix
  20972. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20973. this._useAlternateCameraConfiguration = active;
  20974. };
  20975. Scene.prototype.getViewMatrix = function () {
  20976. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20977. };
  20978. Scene.prototype.getProjectionMatrix = function () {
  20979. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20980. };
  20981. Scene.prototype.getTransformMatrix = function () {
  20982. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20983. };
  20984. Scene.prototype.setTransformMatrix = function (view, projection) {
  20985. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20986. return;
  20987. }
  20988. this._viewUpdateFlag = view.updateFlag;
  20989. this._projectionUpdateFlag = projection.updateFlag;
  20990. this._viewMatrix = view;
  20991. this._projectionMatrix = projection;
  20992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20993. // Update frustum
  20994. if (!this._frustumPlanes) {
  20995. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20996. }
  20997. else {
  20998. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20999. }
  21000. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21001. var otherCamera = this.activeCamera._alternateCamera;
  21002. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21003. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21004. }
  21005. if (this._sceneUbo.useUbo) {
  21006. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21007. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21008. this._sceneUbo.update();
  21009. }
  21010. };
  21011. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21012. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21013. return;
  21014. }
  21015. this._alternateViewUpdateFlag = view.updateFlag;
  21016. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21017. this._alternateViewMatrix = view;
  21018. this._alternateProjectionMatrix = projection;
  21019. if (!this._alternateTransformMatrix) {
  21020. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21021. }
  21022. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21023. if (!this._alternateSceneUbo) {
  21024. this._createAlternateUbo();
  21025. }
  21026. if (this._alternateSceneUbo.useUbo) {
  21027. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21028. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21029. this._alternateSceneUbo.update();
  21030. }
  21031. };
  21032. Scene.prototype.getSceneUniformBuffer = function () {
  21033. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21034. };
  21035. // Methods
  21036. Scene.prototype.getUniqueId = function () {
  21037. var result = Scene._uniqueIdCounter;
  21038. Scene._uniqueIdCounter++;
  21039. return result;
  21040. };
  21041. Scene.prototype.addMesh = function (newMesh) {
  21042. this.meshes.push(newMesh);
  21043. //notify the collision coordinator
  21044. if (this.collisionCoordinator) {
  21045. this.collisionCoordinator.onMeshAdded(newMesh);
  21046. }
  21047. newMesh._resyncLightSources();
  21048. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21049. };
  21050. Scene.prototype.removeMesh = function (toRemove) {
  21051. var index = this.meshes.indexOf(toRemove);
  21052. if (index !== -1) {
  21053. // Remove from the scene if mesh found
  21054. this.meshes.splice(index, 1);
  21055. }
  21056. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21057. return index;
  21058. };
  21059. Scene.prototype.addTransformNode = function (newTransformNode) {
  21060. this.transformNodes.push(newTransformNode);
  21061. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21062. };
  21063. Scene.prototype.removeTransformNode = function (toRemove) {
  21064. var index = this.transformNodes.indexOf(toRemove);
  21065. if (index !== -1) {
  21066. // Remove from the scene if found
  21067. this.transformNodes.splice(index, 1);
  21068. }
  21069. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21070. return index;
  21071. };
  21072. Scene.prototype.removeSkeleton = function (toRemove) {
  21073. var index = this.skeletons.indexOf(toRemove);
  21074. if (index !== -1) {
  21075. // Remove from the scene if found
  21076. this.skeletons.splice(index, 1);
  21077. }
  21078. return index;
  21079. };
  21080. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21081. var index = this.morphTargetManagers.indexOf(toRemove);
  21082. if (index !== -1) {
  21083. // Remove from the scene if found
  21084. this.morphTargetManagers.splice(index, 1);
  21085. }
  21086. return index;
  21087. };
  21088. Scene.prototype.removeLight = function (toRemove) {
  21089. var index = this.lights.indexOf(toRemove);
  21090. if (index !== -1) {
  21091. // Remove from meshes
  21092. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21093. var mesh = _a[_i];
  21094. mesh._removeLightSource(toRemove);
  21095. }
  21096. // Remove from the scene if mesh found
  21097. this.lights.splice(index, 1);
  21098. this.sortLightsByPriority();
  21099. }
  21100. this.onLightRemovedObservable.notifyObservers(toRemove);
  21101. return index;
  21102. };
  21103. Scene.prototype.removeCamera = function (toRemove) {
  21104. var index = this.cameras.indexOf(toRemove);
  21105. if (index !== -1) {
  21106. // Remove from the scene if mesh found
  21107. this.cameras.splice(index, 1);
  21108. }
  21109. // Remove from activeCameras
  21110. var index2 = this.activeCameras.indexOf(toRemove);
  21111. if (index2 !== -1) {
  21112. // Remove from the scene if mesh found
  21113. this.activeCameras.splice(index2, 1);
  21114. }
  21115. // Reset the activeCamera
  21116. if (this.activeCamera === toRemove) {
  21117. if (this.cameras.length > 0) {
  21118. this.activeCamera = this.cameras[0];
  21119. }
  21120. else {
  21121. this.activeCamera = null;
  21122. }
  21123. }
  21124. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21125. return index;
  21126. };
  21127. Scene.prototype.removeParticleSystem = function (toRemove) {
  21128. var index = this.particleSystems.indexOf(toRemove);
  21129. if (index !== -1) {
  21130. this.particleSystems.splice(index, 1);
  21131. }
  21132. return index;
  21133. };
  21134. ;
  21135. Scene.prototype.removeAnimation = function (toRemove) {
  21136. var index = this.animations.indexOf(toRemove);
  21137. if (index !== -1) {
  21138. this.animations.splice(index, 1);
  21139. }
  21140. return index;
  21141. };
  21142. ;
  21143. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21144. var index = this.multiMaterials.indexOf(toRemove);
  21145. if (index !== -1) {
  21146. this.multiMaterials.splice(index, 1);
  21147. }
  21148. return index;
  21149. };
  21150. ;
  21151. Scene.prototype.removeMaterial = function (toRemove) {
  21152. var index = this.materials.indexOf(toRemove);
  21153. if (index !== -1) {
  21154. this.materials.splice(index, 1);
  21155. }
  21156. return index;
  21157. };
  21158. ;
  21159. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21160. var index = this.lensFlareSystems.indexOf(toRemove);
  21161. if (index !== -1) {
  21162. this.lensFlareSystems.splice(index, 1);
  21163. }
  21164. return index;
  21165. };
  21166. ;
  21167. Scene.prototype.removeActionManager = function (toRemove) {
  21168. var index = this._actionManagers.indexOf(toRemove);
  21169. if (index !== -1) {
  21170. this._actionManagers.splice(index, 1);
  21171. }
  21172. return index;
  21173. };
  21174. ;
  21175. Scene.prototype.addLight = function (newLight) {
  21176. this.lights.push(newLight);
  21177. this.sortLightsByPriority();
  21178. // Add light to all meshes (To support if the light is removed and then readded)
  21179. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21180. var mesh = _a[_i];
  21181. if (mesh._lightSources.indexOf(newLight) === -1) {
  21182. mesh._lightSources.push(newLight);
  21183. mesh._resyncLightSources();
  21184. }
  21185. }
  21186. this.onNewLightAddedObservable.notifyObservers(newLight);
  21187. };
  21188. Scene.prototype.sortLightsByPriority = function () {
  21189. if (this.requireLightSorting) {
  21190. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21191. }
  21192. };
  21193. Scene.prototype.addCamera = function (newCamera) {
  21194. this.cameras.push(newCamera);
  21195. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21196. };
  21197. Scene.prototype.addSkeleton = function (newSkeleton) {
  21198. this.skeletons.push(newSkeleton);
  21199. };
  21200. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21201. this.particleSystems.push(newParticleSystem);
  21202. };
  21203. Scene.prototype.addAnimation = function (newAnimation) {
  21204. this.animations.push(newAnimation);
  21205. };
  21206. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21207. this.multiMaterials.push(newMultiMaterial);
  21208. };
  21209. Scene.prototype.addMaterial = function (newMaterial) {
  21210. this.materials.push(newMaterial);
  21211. };
  21212. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21213. this.morphTargetManagers.push(newMorphTargetManager);
  21214. };
  21215. Scene.prototype.addGeometry = function (newGeometrie) {
  21216. this._geometries.push(newGeometrie);
  21217. };
  21218. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21219. this.lensFlareSystems.push(newLensFlareSystem);
  21220. };
  21221. Scene.prototype.addActionManager = function (newActionManager) {
  21222. this._actionManagers.push(newActionManager);
  21223. };
  21224. /**
  21225. * Switch active camera
  21226. * @param {Camera} newCamera - new active camera
  21227. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21228. */
  21229. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21230. if (attachControl === void 0) { attachControl = true; }
  21231. var canvas = this._engine.getRenderingCanvas();
  21232. if (!canvas) {
  21233. return;
  21234. }
  21235. if (this.activeCamera) {
  21236. this.activeCamera.detachControl(canvas);
  21237. }
  21238. this.activeCamera = newCamera;
  21239. if (attachControl) {
  21240. newCamera.attachControl(canvas);
  21241. }
  21242. };
  21243. /**
  21244. * sets the active camera of the scene using its ID
  21245. * @param {string} id - the camera's ID
  21246. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21247. * @see activeCamera
  21248. */
  21249. Scene.prototype.setActiveCameraByID = function (id) {
  21250. var camera = this.getCameraByID(id);
  21251. if (camera) {
  21252. this.activeCamera = camera;
  21253. return camera;
  21254. }
  21255. return null;
  21256. };
  21257. /**
  21258. * sets the active camera of the scene using its name
  21259. * @param {string} name - the camera's name
  21260. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21261. * @see activeCamera
  21262. */
  21263. Scene.prototype.setActiveCameraByName = function (name) {
  21264. var camera = this.getCameraByName(name);
  21265. if (camera) {
  21266. this.activeCamera = camera;
  21267. return camera;
  21268. }
  21269. return null;
  21270. };
  21271. /**
  21272. * get an animation group using its name
  21273. * @param {string} the material's name
  21274. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21275. */
  21276. Scene.prototype.getAnimationGroupByName = function (name) {
  21277. for (var index = 0; index < this.animationGroups.length; index++) {
  21278. if (this.animationGroups[index].name === name) {
  21279. return this.animationGroups[index];
  21280. }
  21281. }
  21282. return null;
  21283. };
  21284. /**
  21285. * get a material using its id
  21286. * @param {string} the material's ID
  21287. * @return {BABYLON.Material|null} the material or null if none found.
  21288. */
  21289. Scene.prototype.getMaterialByID = function (id) {
  21290. for (var index = 0; index < this.materials.length; index++) {
  21291. if (this.materials[index].id === id) {
  21292. return this.materials[index];
  21293. }
  21294. }
  21295. return null;
  21296. };
  21297. /**
  21298. * get a material using its name
  21299. * @param {string} the material's name
  21300. * @return {BABYLON.Material|null} the material or null if none found.
  21301. */
  21302. Scene.prototype.getMaterialByName = function (name) {
  21303. for (var index = 0; index < this.materials.length; index++) {
  21304. if (this.materials[index].name === name) {
  21305. return this.materials[index];
  21306. }
  21307. }
  21308. return null;
  21309. };
  21310. Scene.prototype.getLensFlareSystemByName = function (name) {
  21311. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21312. if (this.lensFlareSystems[index].name === name) {
  21313. return this.lensFlareSystems[index];
  21314. }
  21315. }
  21316. return null;
  21317. };
  21318. Scene.prototype.getLensFlareSystemByID = function (id) {
  21319. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21320. if (this.lensFlareSystems[index].id === id) {
  21321. return this.lensFlareSystems[index];
  21322. }
  21323. }
  21324. return null;
  21325. };
  21326. Scene.prototype.getCameraByID = function (id) {
  21327. for (var index = 0; index < this.cameras.length; index++) {
  21328. if (this.cameras[index].id === id) {
  21329. return this.cameras[index];
  21330. }
  21331. }
  21332. return null;
  21333. };
  21334. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21335. for (var index = 0; index < this.cameras.length; index++) {
  21336. if (this.cameras[index].uniqueId === uniqueId) {
  21337. return this.cameras[index];
  21338. }
  21339. }
  21340. return null;
  21341. };
  21342. /**
  21343. * get a camera using its name
  21344. * @param {string} the camera's name
  21345. * @return {BABYLON.Camera|null} the camera or null if none found.
  21346. */
  21347. Scene.prototype.getCameraByName = function (name) {
  21348. for (var index = 0; index < this.cameras.length; index++) {
  21349. if (this.cameras[index].name === name) {
  21350. return this.cameras[index];
  21351. }
  21352. }
  21353. return null;
  21354. };
  21355. /**
  21356. * get a bone using its id
  21357. * @param {string} the bone's id
  21358. * @return {BABYLON.Bone|null} the bone or null if not found
  21359. */
  21360. Scene.prototype.getBoneByID = function (id) {
  21361. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21362. var skeleton = this.skeletons[skeletonIndex];
  21363. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21364. if (skeleton.bones[boneIndex].id === id) {
  21365. return skeleton.bones[boneIndex];
  21366. }
  21367. }
  21368. }
  21369. return null;
  21370. };
  21371. /**
  21372. * get a bone using its id
  21373. * @param {string} the bone's name
  21374. * @return {BABYLON.Bone|null} the bone or null if not found
  21375. */
  21376. Scene.prototype.getBoneByName = function (name) {
  21377. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21378. var skeleton = this.skeletons[skeletonIndex];
  21379. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21380. if (skeleton.bones[boneIndex].name === name) {
  21381. return skeleton.bones[boneIndex];
  21382. }
  21383. }
  21384. }
  21385. return null;
  21386. };
  21387. /**
  21388. * get a light node using its name
  21389. * @param {string} the light's name
  21390. * @return {BABYLON.Light|null} the light or null if none found.
  21391. */
  21392. Scene.prototype.getLightByName = function (name) {
  21393. for (var index = 0; index < this.lights.length; index++) {
  21394. if (this.lights[index].name === name) {
  21395. return this.lights[index];
  21396. }
  21397. }
  21398. return null;
  21399. };
  21400. /**
  21401. * get a light node using its ID
  21402. * @param {string} the light's id
  21403. * @return {BABYLON.Light|null} the light or null if none found.
  21404. */
  21405. Scene.prototype.getLightByID = function (id) {
  21406. for (var index = 0; index < this.lights.length; index++) {
  21407. if (this.lights[index].id === id) {
  21408. return this.lights[index];
  21409. }
  21410. }
  21411. return null;
  21412. };
  21413. /**
  21414. * get a light node using its scene-generated unique ID
  21415. * @param {number} the light's unique id
  21416. * @return {BABYLON.Light|null} the light or null if none found.
  21417. */
  21418. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21419. for (var index = 0; index < this.lights.length; index++) {
  21420. if (this.lights[index].uniqueId === uniqueId) {
  21421. return this.lights[index];
  21422. }
  21423. }
  21424. return null;
  21425. };
  21426. /**
  21427. * get a particle system by id
  21428. * @param id {number} the particle system id
  21429. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21430. */
  21431. Scene.prototype.getParticleSystemByID = function (id) {
  21432. for (var index = 0; index < this.particleSystems.length; index++) {
  21433. if (this.particleSystems[index].id === id) {
  21434. return this.particleSystems[index];
  21435. }
  21436. }
  21437. return null;
  21438. };
  21439. /**
  21440. * get a geometry using its ID
  21441. * @param {string} the geometry's id
  21442. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21443. */
  21444. Scene.prototype.getGeometryByID = function (id) {
  21445. for (var index = 0; index < this._geometries.length; index++) {
  21446. if (this._geometries[index].id === id) {
  21447. return this._geometries[index];
  21448. }
  21449. }
  21450. return null;
  21451. };
  21452. /**
  21453. * add a new geometry to this scene.
  21454. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21455. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21456. * @return {boolean} was the geometry added or not
  21457. */
  21458. Scene.prototype.pushGeometry = function (geometry, force) {
  21459. if (!force && this.getGeometryByID(geometry.id)) {
  21460. return false;
  21461. }
  21462. this._geometries.push(geometry);
  21463. //notify the collision coordinator
  21464. if (this.collisionCoordinator) {
  21465. this.collisionCoordinator.onGeometryAdded(geometry);
  21466. }
  21467. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21468. return true;
  21469. };
  21470. /**
  21471. * Removes an existing geometry
  21472. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21473. * @return {boolean} was the geometry removed or not
  21474. */
  21475. Scene.prototype.removeGeometry = function (geometry) {
  21476. var index = this._geometries.indexOf(geometry);
  21477. if (index > -1) {
  21478. this._geometries.splice(index, 1);
  21479. //notify the collision coordinator
  21480. if (this.collisionCoordinator) {
  21481. this.collisionCoordinator.onGeometryDeleted(geometry);
  21482. }
  21483. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21484. return true;
  21485. }
  21486. return false;
  21487. };
  21488. Scene.prototype.getGeometries = function () {
  21489. return this._geometries;
  21490. };
  21491. /**
  21492. * Get the first added mesh found of a given ID
  21493. * @param {string} id - the id to search for
  21494. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21495. */
  21496. Scene.prototype.getMeshByID = function (id) {
  21497. for (var index = 0; index < this.meshes.length; index++) {
  21498. if (this.meshes[index].id === id) {
  21499. return this.meshes[index];
  21500. }
  21501. }
  21502. return null;
  21503. };
  21504. Scene.prototype.getMeshesByID = function (id) {
  21505. return this.meshes.filter(function (m) {
  21506. return m.id === id;
  21507. });
  21508. };
  21509. /**
  21510. * Get the first added transform node found of a given ID
  21511. * @param {string} id - the id to search for
  21512. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21513. */
  21514. Scene.prototype.getTransformNodeByID = function (id) {
  21515. for (var index = 0; index < this.transformNodes.length; index++) {
  21516. if (this.transformNodes[index].id === id) {
  21517. return this.transformNodes[index];
  21518. }
  21519. }
  21520. return null;
  21521. };
  21522. Scene.prototype.getTransformNodesByID = function (id) {
  21523. return this.transformNodes.filter(function (m) {
  21524. return m.id === id;
  21525. });
  21526. };
  21527. /**
  21528. * Get a mesh with its auto-generated unique id
  21529. * @param {number} uniqueId - the unique id to search for
  21530. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21531. */
  21532. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21533. for (var index = 0; index < this.meshes.length; index++) {
  21534. if (this.meshes[index].uniqueId === uniqueId) {
  21535. return this.meshes[index];
  21536. }
  21537. }
  21538. return null;
  21539. };
  21540. /**
  21541. * Get a the last added mesh found of a given ID
  21542. * @param {string} id - the id to search for
  21543. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21544. */
  21545. Scene.prototype.getLastMeshByID = function (id) {
  21546. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21547. if (this.meshes[index].id === id) {
  21548. return this.meshes[index];
  21549. }
  21550. }
  21551. return null;
  21552. };
  21553. /**
  21554. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21555. * @param {string} id - the id to search for
  21556. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21557. */
  21558. Scene.prototype.getLastEntryByID = function (id) {
  21559. var index;
  21560. for (index = this.meshes.length - 1; index >= 0; index--) {
  21561. if (this.meshes[index].id === id) {
  21562. return this.meshes[index];
  21563. }
  21564. }
  21565. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21566. if (this.transformNodes[index].id === id) {
  21567. return this.transformNodes[index];
  21568. }
  21569. }
  21570. for (index = this.cameras.length - 1; index >= 0; index--) {
  21571. if (this.cameras[index].id === id) {
  21572. return this.cameras[index];
  21573. }
  21574. }
  21575. for (index = this.lights.length - 1; index >= 0; index--) {
  21576. if (this.lights[index].id === id) {
  21577. return this.lights[index];
  21578. }
  21579. }
  21580. return null;
  21581. };
  21582. Scene.prototype.getNodeByID = function (id) {
  21583. var mesh = this.getMeshByID(id);
  21584. if (mesh) {
  21585. return mesh;
  21586. }
  21587. var light = this.getLightByID(id);
  21588. if (light) {
  21589. return light;
  21590. }
  21591. var camera = this.getCameraByID(id);
  21592. if (camera) {
  21593. return camera;
  21594. }
  21595. var bone = this.getBoneByID(id);
  21596. return bone;
  21597. };
  21598. Scene.prototype.getNodeByName = function (name) {
  21599. var mesh = this.getMeshByName(name);
  21600. if (mesh) {
  21601. return mesh;
  21602. }
  21603. var light = this.getLightByName(name);
  21604. if (light) {
  21605. return light;
  21606. }
  21607. var camera = this.getCameraByName(name);
  21608. if (camera) {
  21609. return camera;
  21610. }
  21611. var bone = this.getBoneByName(name);
  21612. return bone;
  21613. };
  21614. Scene.prototype.getMeshByName = function (name) {
  21615. for (var index = 0; index < this.meshes.length; index++) {
  21616. if (this.meshes[index].name === name) {
  21617. return this.meshes[index];
  21618. }
  21619. }
  21620. return null;
  21621. };
  21622. Scene.prototype.getTransformNodeByName = function (name) {
  21623. for (var index = 0; index < this.transformNodes.length; index++) {
  21624. if (this.transformNodes[index].name === name) {
  21625. return this.transformNodes[index];
  21626. }
  21627. }
  21628. return null;
  21629. };
  21630. Scene.prototype.getSoundByName = function (name) {
  21631. var index;
  21632. if (BABYLON.AudioEngine) {
  21633. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21634. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21635. return this.mainSoundTrack.soundCollection[index];
  21636. }
  21637. }
  21638. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21639. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21640. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21641. return this.soundTracks[sdIndex].soundCollection[index];
  21642. }
  21643. }
  21644. }
  21645. }
  21646. return null;
  21647. };
  21648. Scene.prototype.getLastSkeletonByID = function (id) {
  21649. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21650. if (this.skeletons[index].id === id) {
  21651. return this.skeletons[index];
  21652. }
  21653. }
  21654. return null;
  21655. };
  21656. Scene.prototype.getSkeletonById = function (id) {
  21657. for (var index = 0; index < this.skeletons.length; index++) {
  21658. if (this.skeletons[index].id === id) {
  21659. return this.skeletons[index];
  21660. }
  21661. }
  21662. return null;
  21663. };
  21664. Scene.prototype.getSkeletonByName = function (name) {
  21665. for (var index = 0; index < this.skeletons.length; index++) {
  21666. if (this.skeletons[index].name === name) {
  21667. return this.skeletons[index];
  21668. }
  21669. }
  21670. return null;
  21671. };
  21672. Scene.prototype.getMorphTargetManagerById = function (id) {
  21673. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21674. if (this.morphTargetManagers[index].uniqueId === id) {
  21675. return this.morphTargetManagers[index];
  21676. }
  21677. }
  21678. return null;
  21679. };
  21680. Scene.prototype.isActiveMesh = function (mesh) {
  21681. return (this._activeMeshes.indexOf(mesh) !== -1);
  21682. };
  21683. /**
  21684. * Return a the first highlight layer of the scene with a given name.
  21685. * @param name The name of the highlight layer to look for.
  21686. * @return The highlight layer if found otherwise null.
  21687. */
  21688. Scene.prototype.getHighlightLayerByName = function (name) {
  21689. for (var index = 0; index < this.highlightLayers.length; index++) {
  21690. if (this.highlightLayers[index].name === name) {
  21691. return this.highlightLayers[index];
  21692. }
  21693. }
  21694. return null;
  21695. };
  21696. Object.defineProperty(Scene.prototype, "uid", {
  21697. /**
  21698. * Return a unique id as a string which can serve as an identifier for the scene
  21699. */
  21700. get: function () {
  21701. if (!this._uid) {
  21702. this._uid = BABYLON.Tools.RandomId();
  21703. }
  21704. return this._uid;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. /**
  21710. * Add an externaly attached data from its key.
  21711. * This method call will fail and return false, if such key already exists.
  21712. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21713. * @param key the unique key that identifies the data
  21714. * @param data the data object to associate to the key for this Engine instance
  21715. * @return true if no such key were already present and the data was added successfully, false otherwise
  21716. */
  21717. Scene.prototype.addExternalData = function (key, data) {
  21718. if (!this._externalData) {
  21719. this._externalData = new BABYLON.StringDictionary();
  21720. }
  21721. return this._externalData.add(key, data);
  21722. };
  21723. /**
  21724. * Get an externaly attached data from its key
  21725. * @param key the unique key that identifies the data
  21726. * @return the associated data, if present (can be null), or undefined if not present
  21727. */
  21728. Scene.prototype.getExternalData = function (key) {
  21729. if (!this._externalData) {
  21730. return null;
  21731. }
  21732. return this._externalData.get(key);
  21733. };
  21734. /**
  21735. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21736. * @param key the unique key that identifies the data
  21737. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21738. * @return the associated data, can be null if the factory returned null.
  21739. */
  21740. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21741. if (!this._externalData) {
  21742. this._externalData = new BABYLON.StringDictionary();
  21743. }
  21744. return this._externalData.getOrAddWithFactory(key, factory);
  21745. };
  21746. /**
  21747. * Remove an externaly attached data from the Engine instance
  21748. * @param key the unique key that identifies the data
  21749. * @return true if the data was successfully removed, false if it doesn't exist
  21750. */
  21751. Scene.prototype.removeExternalData = function (key) {
  21752. return this._externalData.remove(key);
  21753. };
  21754. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21755. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21756. if (mesh.showSubMeshesBoundingBox) {
  21757. var boundingInfo = subMesh.getBoundingInfo();
  21758. if (boundingInfo !== null && boundingInfo !== undefined) {
  21759. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21760. }
  21761. }
  21762. var material = subMesh.getMaterial();
  21763. if (material !== null && material !== undefined) {
  21764. // Render targets
  21765. if (material.getRenderTargetTextures !== undefined) {
  21766. if (this._processedMaterials.indexOf(material) === -1) {
  21767. this._processedMaterials.push(material);
  21768. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21769. }
  21770. }
  21771. // Dispatch
  21772. this._activeIndices.addCount(subMesh.indexCount, false);
  21773. this._renderingManager.dispatch(subMesh, mesh, material);
  21774. }
  21775. }
  21776. };
  21777. Scene.prototype._isInIntermediateRendering = function () {
  21778. return this._intermediateRendering;
  21779. };
  21780. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21781. this._activeMeshCandidateProvider = provider;
  21782. };
  21783. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21784. return this._activeMeshCandidateProvider;
  21785. };
  21786. /**
  21787. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21788. */
  21789. Scene.prototype.freezeActiveMeshes = function () {
  21790. this._evaluateActiveMeshes();
  21791. this._activeMeshesFrozen = true;
  21792. return this;
  21793. };
  21794. /**
  21795. * Use this function to restart evaluating active meshes on every frame
  21796. */
  21797. Scene.prototype.unfreezeActiveMeshes = function () {
  21798. this._activeMeshesFrozen = false;
  21799. return this;
  21800. };
  21801. Scene.prototype._evaluateActiveMeshes = function () {
  21802. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21803. return;
  21804. }
  21805. if (!this.activeCamera) {
  21806. return;
  21807. }
  21808. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21809. this.activeCamera._activeMeshes.reset();
  21810. this._activeMeshes.reset();
  21811. this._renderingManager.reset();
  21812. this._processedMaterials.reset();
  21813. this._activeParticleSystems.reset();
  21814. this._activeSkeletons.reset();
  21815. this._softwareSkinnedMeshes.reset();
  21816. if (this._boundingBoxRenderer) {
  21817. this._boundingBoxRenderer.reset();
  21818. }
  21819. // Meshes
  21820. var meshes;
  21821. var len;
  21822. var checkIsEnabled = true;
  21823. // Determine mesh candidates
  21824. if (this._activeMeshCandidateProvider !== undefined) {
  21825. // Use _activeMeshCandidateProvider
  21826. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21827. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21828. if (meshes !== undefined) {
  21829. len = meshes.length;
  21830. }
  21831. else {
  21832. len = 0;
  21833. }
  21834. }
  21835. else if (this._selectionOctree !== undefined) {
  21836. // Octree
  21837. var selection = this._selectionOctree.select(this._frustumPlanes);
  21838. meshes = selection.data;
  21839. len = selection.length;
  21840. }
  21841. else {
  21842. // Full scene traversal
  21843. len = this.meshes.length;
  21844. meshes = this.meshes;
  21845. }
  21846. // Check each mesh
  21847. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21848. mesh = meshes[meshIndex];
  21849. if (mesh.isBlocked) {
  21850. continue;
  21851. }
  21852. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21853. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21854. continue;
  21855. }
  21856. mesh.computeWorldMatrix();
  21857. // Intersections
  21858. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21859. this._meshesForIntersections.pushNoDuplicate(mesh);
  21860. }
  21861. // Switch to current LOD
  21862. meshLOD = mesh.getLOD(this.activeCamera);
  21863. if (meshLOD === undefined || meshLOD === null) {
  21864. continue;
  21865. }
  21866. mesh._preActivate();
  21867. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21868. this._activeMeshes.push(mesh);
  21869. this.activeCamera._activeMeshes.push(mesh);
  21870. mesh._activate(this._renderId);
  21871. if (meshLOD !== mesh) {
  21872. meshLOD._activate(this._renderId);
  21873. }
  21874. this._activeMesh(mesh, meshLOD);
  21875. }
  21876. }
  21877. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21878. // Particle systems
  21879. if (this.particlesEnabled) {
  21880. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21881. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21882. var particleSystem = this.particleSystems[particleIndex];
  21883. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21884. continue;
  21885. }
  21886. var emitter = particleSystem.emitter;
  21887. if (!emitter.position || emitter.isEnabled()) {
  21888. this._activeParticleSystems.push(particleSystem);
  21889. particleSystem.animate();
  21890. this._renderingManager.dispatchParticles(particleSystem);
  21891. }
  21892. }
  21893. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21894. }
  21895. };
  21896. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21897. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21898. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21899. mesh.skeleton.prepare();
  21900. }
  21901. if (!mesh.computeBonesUsingShaders) {
  21902. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21903. }
  21904. }
  21905. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21906. var boundingInfo = sourceMesh.getBoundingInfo();
  21907. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21908. }
  21909. if (mesh !== undefined && mesh !== null
  21910. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21911. // Submeshes Octrees
  21912. var len;
  21913. var subMeshes;
  21914. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21915. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21916. len = intersections.length;
  21917. subMeshes = intersections.data;
  21918. }
  21919. else {
  21920. subMeshes = mesh.subMeshes;
  21921. len = subMeshes.length;
  21922. }
  21923. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21924. subMesh = subMeshes[subIndex];
  21925. this._evaluateSubMesh(subMesh, mesh);
  21926. }
  21927. }
  21928. };
  21929. Scene.prototype.updateTransformMatrix = function (force) {
  21930. if (!this.activeCamera) {
  21931. return;
  21932. }
  21933. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21934. };
  21935. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21936. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21937. };
  21938. Scene.prototype._renderForCamera = function (camera) {
  21939. if (camera && camera._skipRendering) {
  21940. return;
  21941. }
  21942. var engine = this._engine;
  21943. this.activeCamera = camera;
  21944. if (!this.activeCamera)
  21945. throw new Error("Active camera not set");
  21946. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21947. // Viewport
  21948. engine.setViewport(this.activeCamera.viewport);
  21949. // Camera
  21950. this.resetCachedMaterial();
  21951. this._renderId++;
  21952. this.activeCamera.update();
  21953. this.updateTransformMatrix();
  21954. if (camera._alternateCamera) {
  21955. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21956. this._alternateRendering = true;
  21957. }
  21958. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21959. // Meshes
  21960. this._evaluateActiveMeshes();
  21961. // Software skinning
  21962. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21963. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21964. mesh.applySkeleton(mesh.skeleton);
  21965. }
  21966. // Render targets
  21967. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21968. var needsRestoreFrameBuffer = false;
  21969. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21970. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21971. }
  21972. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21973. this._intermediateRendering = true;
  21974. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21975. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21976. var renderTarget = this._renderTargets.data[renderIndex];
  21977. if (renderTarget._shouldRender()) {
  21978. this._renderId++;
  21979. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21980. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21981. }
  21982. }
  21983. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21984. this._intermediateRendering = false;
  21985. this._renderId++;
  21986. needsRestoreFrameBuffer = true; // Restore back buffer
  21987. }
  21988. // Render HighlightLayer Texture
  21989. var stencilState = this._engine.getStencilBuffer();
  21990. var renderhighlights = false;
  21991. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21992. this._intermediateRendering = true;
  21993. for (var i = 0; i < this.highlightLayers.length; i++) {
  21994. var highlightLayer = this.highlightLayers[i];
  21995. if (highlightLayer.shouldRender() &&
  21996. (!highlightLayer.camera ||
  21997. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21998. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21999. renderhighlights = true;
  22000. var renderTarget = highlightLayer._mainTexture;
  22001. if (renderTarget._shouldRender()) {
  22002. this._renderId++;
  22003. renderTarget.render(false, false);
  22004. needsRestoreFrameBuffer = true;
  22005. }
  22006. }
  22007. }
  22008. this._intermediateRendering = false;
  22009. this._renderId++;
  22010. }
  22011. if (needsRestoreFrameBuffer) {
  22012. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22013. }
  22014. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22015. // Prepare Frame
  22016. this.postProcessManager._prepareFrame();
  22017. // Backgrounds
  22018. var layerIndex;
  22019. var layer;
  22020. if (this.layers.length) {
  22021. engine.setDepthBuffer(false);
  22022. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22023. layer = this.layers[layerIndex];
  22024. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22025. layer.render();
  22026. }
  22027. }
  22028. engine.setDepthBuffer(true);
  22029. }
  22030. // Activate HighlightLayer stencil
  22031. if (renderhighlights) {
  22032. this._engine.setStencilBuffer(true);
  22033. }
  22034. // Render
  22035. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22036. this._renderingManager.render(null, null, true, true);
  22037. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22038. // Restore HighlightLayer stencil
  22039. if (renderhighlights) {
  22040. this._engine.setStencilBuffer(stencilState);
  22041. }
  22042. // Bounding boxes
  22043. if (this._boundingBoxRenderer) {
  22044. this._boundingBoxRenderer.render();
  22045. }
  22046. // Lens flares
  22047. if (this.lensFlaresEnabled) {
  22048. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22049. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22050. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22051. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22052. lensFlareSystem.render();
  22053. }
  22054. }
  22055. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22056. }
  22057. // Foregrounds
  22058. if (this.layers.length) {
  22059. engine.setDepthBuffer(false);
  22060. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22061. layer = this.layers[layerIndex];
  22062. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22063. layer.render();
  22064. }
  22065. }
  22066. engine.setDepthBuffer(true);
  22067. }
  22068. // Highlight Layer
  22069. if (renderhighlights) {
  22070. engine.setDepthBuffer(false);
  22071. for (var i = 0; i < this.highlightLayers.length; i++) {
  22072. if (this.highlightLayers[i].shouldRender()) {
  22073. this.highlightLayers[i].render();
  22074. }
  22075. }
  22076. engine.setDepthBuffer(true);
  22077. }
  22078. // Finalize frame
  22079. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22080. // Reset some special arrays
  22081. this._renderTargets.reset();
  22082. this._alternateRendering = false;
  22083. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22084. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22085. };
  22086. Scene.prototype._processSubCameras = function (camera) {
  22087. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22088. this._renderForCamera(camera);
  22089. return;
  22090. }
  22091. // Update camera
  22092. if (this.activeCamera) {
  22093. this.activeCamera.update();
  22094. }
  22095. // rig cameras
  22096. for (var index = 0; index < camera._rigCameras.length; index++) {
  22097. this._renderForCamera(camera._rigCameras[index]);
  22098. }
  22099. this.activeCamera = camera;
  22100. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22101. };
  22102. Scene.prototype._checkIntersections = function () {
  22103. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22104. var sourceMesh = this._meshesForIntersections.data[index];
  22105. if (!sourceMesh.actionManager) {
  22106. continue;
  22107. }
  22108. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22109. var action = sourceMesh.actionManager.actions[actionIndex];
  22110. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22111. var parameters = action.getTriggerParameter();
  22112. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22113. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22114. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22115. if (areIntersecting && currentIntersectionInProgress === -1) {
  22116. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22117. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22118. sourceMesh._intersectionsInProgress.push(otherMesh);
  22119. }
  22120. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22121. sourceMesh._intersectionsInProgress.push(otherMesh);
  22122. }
  22123. }
  22124. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22125. //They intersected, and now they don't.
  22126. //is this trigger an exit trigger? execute an event.
  22127. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22128. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22129. }
  22130. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22131. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22132. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22133. }
  22134. }
  22135. }
  22136. }
  22137. }
  22138. };
  22139. Scene.prototype.render = function () {
  22140. if (this.isDisposed) {
  22141. return;
  22142. }
  22143. this._activeParticles.fetchNewFrame();
  22144. this._totalVertices.fetchNewFrame();
  22145. this._activeIndices.fetchNewFrame();
  22146. this._activeBones.fetchNewFrame();
  22147. this._meshesForIntersections.reset();
  22148. this.resetCachedMaterial();
  22149. this.onBeforeAnimationsObservable.notifyObservers(this);
  22150. // Actions
  22151. if (this.actionManager) {
  22152. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22153. }
  22154. //Simplification Queue
  22155. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22156. this.simplificationQueue.executeNext();
  22157. }
  22158. if (this._engine.isDeterministicLockStep()) {
  22159. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22160. var defaultFPS = (60.0 / 1000.0);
  22161. var defaultFrameTime = 1000 / 60; // frame time in MS
  22162. if (this._physicsEngine) {
  22163. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22164. }
  22165. var stepsTaken = 0;
  22166. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22167. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22168. internalSteps = Math.min(internalSteps, maxSubSteps);
  22169. do {
  22170. this.onBeforeStepObservable.notifyObservers(this);
  22171. // Animations
  22172. this._animationRatio = defaultFrameTime * defaultFPS;
  22173. this._animate();
  22174. this.onAfterAnimationsObservable.notifyObservers(this);
  22175. // Physics
  22176. if (this._physicsEngine) {
  22177. this.onBeforePhysicsObservable.notifyObservers(this);
  22178. this._physicsEngine._step(defaultFrameTime / 1000);
  22179. this.onAfterPhysicsObservable.notifyObservers(this);
  22180. }
  22181. this.onAfterStepObservable.notifyObservers(this);
  22182. this._currentStepId++;
  22183. stepsTaken++;
  22184. deltaTime -= defaultFrameTime;
  22185. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22186. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22187. }
  22188. else {
  22189. // Animations
  22190. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22191. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22192. this._animate();
  22193. this.onAfterAnimationsObservable.notifyObservers(this);
  22194. // Physics
  22195. if (this._physicsEngine) {
  22196. this.onBeforePhysicsObservable.notifyObservers(this);
  22197. this._physicsEngine._step(deltaTime / 1000.0);
  22198. this.onAfterPhysicsObservable.notifyObservers(this);
  22199. }
  22200. }
  22201. // update gamepad manager
  22202. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22203. this._gamepadManager._checkGamepadsStatus();
  22204. }
  22205. // Before render
  22206. this.onBeforeRenderObservable.notifyObservers(this);
  22207. // Customs render targets
  22208. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22209. var engine = this.getEngine();
  22210. var currentActiveCamera = this.activeCamera;
  22211. if (this.renderTargetsEnabled) {
  22212. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22213. this._intermediateRendering = true;
  22214. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22215. var renderTarget = this.customRenderTargets[customIndex];
  22216. if (renderTarget._shouldRender()) {
  22217. this._renderId++;
  22218. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22219. if (!this.activeCamera)
  22220. throw new Error("Active camera not set");
  22221. // Viewport
  22222. engine.setViewport(this.activeCamera.viewport);
  22223. // Camera
  22224. this.updateTransformMatrix();
  22225. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22226. }
  22227. }
  22228. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22229. this._intermediateRendering = false;
  22230. this._renderId++;
  22231. }
  22232. // Restore back buffer
  22233. if (this.customRenderTargets.length > 0) {
  22234. engine.restoreDefaultFramebuffer();
  22235. }
  22236. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22237. this.activeCamera = currentActiveCamera;
  22238. // Procedural textures
  22239. if (this.proceduralTexturesEnabled) {
  22240. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22241. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22242. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22243. if (proceduralTexture._shouldRender()) {
  22244. proceduralTexture.render();
  22245. }
  22246. }
  22247. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22248. }
  22249. // Clear
  22250. if (this.autoClearDepthAndStencil || this.autoClear) {
  22251. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22252. }
  22253. // Shadows
  22254. if (this.shadowsEnabled) {
  22255. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22256. var light = this.lights[lightIndex];
  22257. var shadowGenerator = light.getShadowGenerator();
  22258. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22259. var shadowMap = (shadowGenerator.getShadowMap());
  22260. if (this.textures.indexOf(shadowMap) !== -1) {
  22261. this._renderTargets.push(shadowMap);
  22262. }
  22263. }
  22264. }
  22265. }
  22266. // Depth renderer
  22267. if (this._depthRenderer) {
  22268. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22269. }
  22270. // Geometry renderer
  22271. if (this._geometryBufferRenderer) {
  22272. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22273. }
  22274. // RenderPipeline
  22275. if (this._postProcessRenderPipelineManager) {
  22276. this._postProcessRenderPipelineManager.update();
  22277. }
  22278. // Multi-cameras?
  22279. if (this.activeCameras.length > 0) {
  22280. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22281. if (cameraIndex > 0) {
  22282. this._engine.clear(null, false, true, true);
  22283. }
  22284. this._processSubCameras(this.activeCameras[cameraIndex]);
  22285. }
  22286. }
  22287. else {
  22288. if (!this.activeCamera) {
  22289. throw new Error("No camera defined");
  22290. }
  22291. this._processSubCameras(this.activeCamera);
  22292. }
  22293. // Intersection checks
  22294. this._checkIntersections();
  22295. // Update the audio listener attached to the camera
  22296. if (BABYLON.AudioEngine) {
  22297. this._updateAudioParameters();
  22298. }
  22299. // After render
  22300. if (this.afterRender) {
  22301. this.afterRender();
  22302. }
  22303. this.onAfterRenderObservable.notifyObservers(this);
  22304. // Cleaning
  22305. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22306. var data = this._toBeDisposed.data[index];
  22307. if (data) {
  22308. data.dispose();
  22309. }
  22310. this._toBeDisposed[index] = null;
  22311. }
  22312. this._toBeDisposed.reset();
  22313. if (this.dumpNextRenderTargets) {
  22314. this.dumpNextRenderTargets = false;
  22315. }
  22316. this._activeBones.addCount(0, true);
  22317. this._activeIndices.addCount(0, true);
  22318. this._activeParticles.addCount(0, true);
  22319. };
  22320. Scene.prototype._updateAudioParameters = function () {
  22321. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22322. return;
  22323. }
  22324. var listeningCamera;
  22325. var audioEngine = BABYLON.Engine.audioEngine;
  22326. if (this.activeCameras.length > 0) {
  22327. listeningCamera = this.activeCameras[0];
  22328. }
  22329. else {
  22330. listeningCamera = this.activeCamera;
  22331. }
  22332. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22333. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22334. // for VR cameras
  22335. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22336. listeningCamera = listeningCamera.rigCameras[0];
  22337. }
  22338. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22339. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22340. cameraDirection.normalize();
  22341. // To avoid some errors on GearVR
  22342. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22343. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22344. }
  22345. var i;
  22346. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22347. var sound = this.mainSoundTrack.soundCollection[i];
  22348. if (sound.useCustomAttenuation) {
  22349. sound.updateDistanceFromListener();
  22350. }
  22351. }
  22352. for (i = 0; i < this.soundTracks.length; i++) {
  22353. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22354. sound = this.soundTracks[i].soundCollection[j];
  22355. if (sound.useCustomAttenuation) {
  22356. sound.updateDistanceFromListener();
  22357. }
  22358. }
  22359. }
  22360. }
  22361. };
  22362. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22363. // Audio
  22364. get: function () {
  22365. return this._audioEnabled;
  22366. },
  22367. set: function (value) {
  22368. this._audioEnabled = value;
  22369. if (BABYLON.AudioEngine) {
  22370. if (this._audioEnabled) {
  22371. this._enableAudio();
  22372. }
  22373. else {
  22374. this._disableAudio();
  22375. }
  22376. }
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Scene.prototype._disableAudio = function () {
  22382. var i;
  22383. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22384. this.mainSoundTrack.soundCollection[i].pause();
  22385. }
  22386. for (i = 0; i < this.soundTracks.length; i++) {
  22387. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22388. this.soundTracks[i].soundCollection[j].pause();
  22389. }
  22390. }
  22391. };
  22392. Scene.prototype._enableAudio = function () {
  22393. var i;
  22394. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22395. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22396. this.mainSoundTrack.soundCollection[i].play();
  22397. }
  22398. }
  22399. for (i = 0; i < this.soundTracks.length; i++) {
  22400. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22401. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22402. this.soundTracks[i].soundCollection[j].play();
  22403. }
  22404. }
  22405. }
  22406. };
  22407. Object.defineProperty(Scene.prototype, "headphone", {
  22408. get: function () {
  22409. return this._headphone;
  22410. },
  22411. set: function (value) {
  22412. this._headphone = value;
  22413. if (BABYLON.AudioEngine) {
  22414. if (this._headphone) {
  22415. this._switchAudioModeForHeadphones();
  22416. }
  22417. else {
  22418. this._switchAudioModeForNormalSpeakers();
  22419. }
  22420. }
  22421. },
  22422. enumerable: true,
  22423. configurable: true
  22424. });
  22425. Scene.prototype._switchAudioModeForHeadphones = function () {
  22426. this.mainSoundTrack.switchPanningModelToHRTF();
  22427. for (var i = 0; i < this.soundTracks.length; i++) {
  22428. this.soundTracks[i].switchPanningModelToHRTF();
  22429. }
  22430. };
  22431. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22432. this.mainSoundTrack.switchPanningModelToEqualPower();
  22433. for (var i = 0; i < this.soundTracks.length; i++) {
  22434. this.soundTracks[i].switchPanningModelToEqualPower();
  22435. }
  22436. };
  22437. Scene.prototype.enableDepthRenderer = function () {
  22438. if (this._depthRenderer) {
  22439. return this._depthRenderer;
  22440. }
  22441. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22442. return this._depthRenderer;
  22443. };
  22444. Scene.prototype.disableDepthRenderer = function () {
  22445. if (!this._depthRenderer) {
  22446. return;
  22447. }
  22448. this._depthRenderer.dispose();
  22449. this._depthRenderer = null;
  22450. };
  22451. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22452. if (ratio === void 0) { ratio = 1; }
  22453. if (this._geometryBufferRenderer) {
  22454. return this._geometryBufferRenderer;
  22455. }
  22456. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22457. if (!this._geometryBufferRenderer.isSupported) {
  22458. this._geometryBufferRenderer = null;
  22459. }
  22460. return this._geometryBufferRenderer;
  22461. };
  22462. Scene.prototype.disableGeometryBufferRenderer = function () {
  22463. if (!this._geometryBufferRenderer) {
  22464. return;
  22465. }
  22466. this._geometryBufferRenderer.dispose();
  22467. this._geometryBufferRenderer = null;
  22468. };
  22469. Scene.prototype.freezeMaterials = function () {
  22470. for (var i = 0; i < this.materials.length; i++) {
  22471. this.materials[i].freeze();
  22472. }
  22473. };
  22474. Scene.prototype.unfreezeMaterials = function () {
  22475. for (var i = 0; i < this.materials.length; i++) {
  22476. this.materials[i].unfreeze();
  22477. }
  22478. };
  22479. Scene.prototype.dispose = function () {
  22480. this.beforeRender = null;
  22481. this.afterRender = null;
  22482. this.skeletons = [];
  22483. this.morphTargetManagers = [];
  22484. this.importedMeshesFiles = new Array();
  22485. this.stopAllAnimations();
  22486. this.resetCachedMaterial();
  22487. if (this._depthRenderer) {
  22488. this._depthRenderer.dispose();
  22489. }
  22490. if (this._gamepadManager) {
  22491. this._gamepadManager.dispose();
  22492. this._gamepadManager = null;
  22493. }
  22494. // Smart arrays
  22495. if (this.activeCamera) {
  22496. this.activeCamera._activeMeshes.dispose();
  22497. this.activeCamera = null;
  22498. }
  22499. this._activeMeshes.dispose();
  22500. this._renderingManager.dispose();
  22501. this._processedMaterials.dispose();
  22502. this._activeParticleSystems.dispose();
  22503. this._activeSkeletons.dispose();
  22504. this._softwareSkinnedMeshes.dispose();
  22505. this._renderTargets.dispose();
  22506. if (this._boundingBoxRenderer) {
  22507. this._boundingBoxRenderer.dispose();
  22508. }
  22509. this._meshesForIntersections.dispose();
  22510. this._toBeDisposed.dispose();
  22511. // Abort active requests
  22512. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22513. var request = _a[_i];
  22514. request.abort();
  22515. }
  22516. // Debug layer
  22517. if (this._debugLayer) {
  22518. this._debugLayer.hide();
  22519. }
  22520. // Events
  22521. this.onDisposeObservable.notifyObservers(this);
  22522. this.onDisposeObservable.clear();
  22523. this.onBeforeRenderObservable.clear();
  22524. this.onAfterRenderObservable.clear();
  22525. this.OnBeforeRenderTargetsRenderObservable.clear();
  22526. this.OnAfterRenderTargetsRenderObservable.clear();
  22527. this.onAfterStepObservable.clear();
  22528. this.onBeforeStepObservable.clear();
  22529. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22530. this.onAfterActiveMeshesEvaluationObservable.clear();
  22531. this.onBeforeParticlesRenderingObservable.clear();
  22532. this.onAfterParticlesRenderingObservable.clear();
  22533. this.onBeforeSpritesRenderingObservable.clear();
  22534. this.onAfterSpritesRenderingObservable.clear();
  22535. this.onBeforeDrawPhaseObservable.clear();
  22536. this.onAfterDrawPhaseObservable.clear();
  22537. this.onBeforePhysicsObservable.clear();
  22538. this.onAfterPhysicsObservable.clear();
  22539. this.onBeforeAnimationsObservable.clear();
  22540. this.onAfterAnimationsObservable.clear();
  22541. this.onDataLoadedObservable.clear();
  22542. this.detachControl();
  22543. // Release sounds & sounds tracks
  22544. if (BABYLON.AudioEngine) {
  22545. this.disposeSounds();
  22546. }
  22547. // VR Helper
  22548. if (this.VRHelper) {
  22549. this.VRHelper.dispose();
  22550. }
  22551. // Detach cameras
  22552. var canvas = this._engine.getRenderingCanvas();
  22553. if (canvas) {
  22554. var index;
  22555. for (index = 0; index < this.cameras.length; index++) {
  22556. this.cameras[index].detachControl(canvas);
  22557. }
  22558. }
  22559. // Release animation groups
  22560. while (this.animationGroups.length) {
  22561. this.animationGroups[0].dispose();
  22562. }
  22563. // Release lights
  22564. while (this.lights.length) {
  22565. this.lights[0].dispose();
  22566. }
  22567. // Release meshes
  22568. while (this.meshes.length) {
  22569. this.meshes[0].dispose(true);
  22570. }
  22571. while (this.transformNodes.length) {
  22572. this.removeTransformNode(this.transformNodes[0]);
  22573. }
  22574. // Release cameras
  22575. while (this.cameras.length) {
  22576. this.cameras[0].dispose();
  22577. }
  22578. // Release materials
  22579. if (this.defaultMaterial) {
  22580. this.defaultMaterial.dispose();
  22581. }
  22582. while (this.multiMaterials.length) {
  22583. this.multiMaterials[0].dispose();
  22584. }
  22585. while (this.materials.length) {
  22586. this.materials[0].dispose();
  22587. }
  22588. // Release particles
  22589. while (this.particleSystems.length) {
  22590. this.particleSystems[0].dispose();
  22591. }
  22592. // Release sprites
  22593. while (this.spriteManagers.length) {
  22594. this.spriteManagers[0].dispose();
  22595. }
  22596. // Release postProcesses
  22597. while (this.postProcesses.length) {
  22598. this.postProcesses[0].dispose();
  22599. }
  22600. // Release layers
  22601. while (this.layers.length) {
  22602. this.layers[0].dispose();
  22603. }
  22604. while (this.highlightLayers.length) {
  22605. this.highlightLayers[0].dispose();
  22606. }
  22607. // Release textures
  22608. while (this.textures.length) {
  22609. this.textures[0].dispose();
  22610. }
  22611. // Release UBO
  22612. this._sceneUbo.dispose();
  22613. if (this._alternateSceneUbo) {
  22614. this._alternateSceneUbo.dispose();
  22615. }
  22616. // Post-processes
  22617. this.postProcessManager.dispose();
  22618. if (this._postProcessRenderPipelineManager) {
  22619. this._postProcessRenderPipelineManager.dispose();
  22620. }
  22621. // Physics
  22622. if (this._physicsEngine) {
  22623. this.disablePhysicsEngine();
  22624. }
  22625. // Remove from engine
  22626. index = this._engine.scenes.indexOf(this);
  22627. if (index > -1) {
  22628. this._engine.scenes.splice(index, 1);
  22629. }
  22630. this._engine.wipeCaches(true);
  22631. this._isDisposed = true;
  22632. };
  22633. Object.defineProperty(Scene.prototype, "isDisposed", {
  22634. get: function () {
  22635. return this._isDisposed;
  22636. },
  22637. enumerable: true,
  22638. configurable: true
  22639. });
  22640. // Release sounds & sounds tracks
  22641. Scene.prototype.disposeSounds = function () {
  22642. if (!this._mainSoundTrack) {
  22643. return;
  22644. }
  22645. this.mainSoundTrack.dispose();
  22646. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22647. this.soundTracks[scIndex].dispose();
  22648. }
  22649. };
  22650. // Octrees
  22651. Scene.prototype.getWorldExtends = function () {
  22652. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22653. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22654. for (var index = 0; index < this.meshes.length; index++) {
  22655. var mesh = this.meshes[index];
  22656. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22657. continue;
  22658. }
  22659. mesh.computeWorldMatrix(true);
  22660. var boundingInfo = mesh.getBoundingInfo();
  22661. var minBox = boundingInfo.boundingBox.minimumWorld;
  22662. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22663. BABYLON.Tools.CheckExtends(minBox, min, max);
  22664. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22665. }
  22666. return {
  22667. min: min,
  22668. max: max
  22669. };
  22670. };
  22671. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22672. if (maxCapacity === void 0) { maxCapacity = 64; }
  22673. if (maxDepth === void 0) { maxDepth = 2; }
  22674. if (!this._selectionOctree) {
  22675. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22676. }
  22677. var worldExtends = this.getWorldExtends();
  22678. // Update octree
  22679. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22680. return this._selectionOctree;
  22681. };
  22682. // Picking
  22683. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22684. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22685. var result = BABYLON.Ray.Zero();
  22686. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22687. return result;
  22688. };
  22689. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22690. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22691. var engine = this._engine;
  22692. if (!camera) {
  22693. if (!this.activeCamera)
  22694. throw new Error("Active camera not set");
  22695. camera = this.activeCamera;
  22696. }
  22697. var cameraViewport = camera.viewport;
  22698. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22699. // Moving coordinates to local viewport world
  22700. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22701. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22702. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22703. return this;
  22704. };
  22705. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22706. var result = BABYLON.Ray.Zero();
  22707. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22708. return result;
  22709. };
  22710. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22711. if (!BABYLON.PickingInfo) {
  22712. return this;
  22713. }
  22714. var engine = this._engine;
  22715. if (!camera) {
  22716. if (!this.activeCamera)
  22717. throw new Error("Active camera not set");
  22718. camera = this.activeCamera;
  22719. }
  22720. var cameraViewport = camera.viewport;
  22721. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22722. var identity = BABYLON.Matrix.Identity();
  22723. // Moving coordinates to local viewport world
  22724. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22725. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22726. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22727. return this;
  22728. };
  22729. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22730. if (!BABYLON.PickingInfo) {
  22731. return null;
  22732. }
  22733. var pickingInfo = null;
  22734. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22735. var mesh = this.meshes[meshIndex];
  22736. if (predicate) {
  22737. if (!predicate(mesh)) {
  22738. continue;
  22739. }
  22740. }
  22741. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22742. continue;
  22743. }
  22744. var world = mesh.getWorldMatrix();
  22745. var ray = rayFunction(world);
  22746. var result = mesh.intersects(ray, fastCheck);
  22747. if (!result || !result.hit)
  22748. continue;
  22749. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22750. continue;
  22751. pickingInfo = result;
  22752. if (fastCheck) {
  22753. break;
  22754. }
  22755. }
  22756. return pickingInfo || new BABYLON.PickingInfo();
  22757. };
  22758. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22759. if (!BABYLON.PickingInfo) {
  22760. return null;
  22761. }
  22762. var pickingInfos = new Array();
  22763. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22764. var mesh = this.meshes[meshIndex];
  22765. if (predicate) {
  22766. if (!predicate(mesh)) {
  22767. continue;
  22768. }
  22769. }
  22770. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22771. continue;
  22772. }
  22773. var world = mesh.getWorldMatrix();
  22774. var ray = rayFunction(world);
  22775. var result = mesh.intersects(ray, false);
  22776. if (!result || !result.hit)
  22777. continue;
  22778. pickingInfos.push(result);
  22779. }
  22780. return pickingInfos;
  22781. };
  22782. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22783. if (!BABYLON.PickingInfo) {
  22784. return null;
  22785. }
  22786. var pickingInfo = null;
  22787. if (!camera) {
  22788. if (!this.activeCamera) {
  22789. return null;
  22790. }
  22791. camera = this.activeCamera;
  22792. }
  22793. if (this.spriteManagers.length > 0) {
  22794. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22795. var spriteManager = this.spriteManagers[spriteIndex];
  22796. if (!spriteManager.isPickable) {
  22797. continue;
  22798. }
  22799. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22800. if (!result || !result.hit)
  22801. continue;
  22802. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22803. continue;
  22804. pickingInfo = result;
  22805. if (fastCheck) {
  22806. break;
  22807. }
  22808. }
  22809. }
  22810. return pickingInfo || new BABYLON.PickingInfo();
  22811. };
  22812. /** Launch a ray to try to pick a mesh in the scene
  22813. * @param x position on screen
  22814. * @param y position on screen
  22815. * @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
  22816. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22817. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22818. */
  22819. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22820. var _this = this;
  22821. if (!BABYLON.PickingInfo) {
  22822. return null;
  22823. }
  22824. return this._internalPick(function (world) {
  22825. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22826. return _this._tempPickingRay;
  22827. }, predicate, fastCheck);
  22828. };
  22829. /** Launch a ray to try to pick a sprite in the scene
  22830. * @param x position on screen
  22831. * @param y position on screen
  22832. * @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
  22833. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22834. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22835. */
  22836. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22837. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22838. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22839. };
  22840. /** Use the given ray to pick a mesh in the scene
  22841. * @param ray The ray to use to pick meshes
  22842. * @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
  22843. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22844. */
  22845. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22846. var _this = this;
  22847. return this._internalPick(function (world) {
  22848. if (!_this._pickWithRayInverseMatrix) {
  22849. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22850. }
  22851. world.invertToRef(_this._pickWithRayInverseMatrix);
  22852. if (!_this._cachedRayForTransform) {
  22853. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22854. }
  22855. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22856. return _this._cachedRayForTransform;
  22857. }, predicate, fastCheck);
  22858. };
  22859. /**
  22860. * Launch a ray to try to pick a mesh in the scene
  22861. * @param x X position on screen
  22862. * @param y Y position on screen
  22863. * @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
  22864. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22865. */
  22866. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22867. var _this = this;
  22868. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22869. };
  22870. /**
  22871. * Launch a ray to try to pick a mesh in the scene
  22872. * @param ray Ray to use
  22873. * @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
  22874. */
  22875. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22876. var _this = this;
  22877. return this._internalMultiPick(function (world) {
  22878. if (!_this._pickWithRayInverseMatrix) {
  22879. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22880. }
  22881. world.invertToRef(_this._pickWithRayInverseMatrix);
  22882. if (!_this._cachedRayForTransform) {
  22883. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22884. }
  22885. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22886. return _this._cachedRayForTransform;
  22887. }, predicate);
  22888. };
  22889. Scene.prototype.setPointerOverMesh = function (mesh) {
  22890. if (this._pointerOverMesh === mesh) {
  22891. return;
  22892. }
  22893. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22894. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22895. }
  22896. this._pointerOverMesh = mesh;
  22897. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22898. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22899. }
  22900. };
  22901. Scene.prototype.getPointerOverMesh = function () {
  22902. return this._pointerOverMesh;
  22903. };
  22904. Scene.prototype.setPointerOverSprite = function (sprite) {
  22905. if (this._pointerOverSprite === sprite) {
  22906. return;
  22907. }
  22908. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22909. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22910. }
  22911. this._pointerOverSprite = sprite;
  22912. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22913. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22914. }
  22915. };
  22916. Scene.prototype.getPointerOverSprite = function () {
  22917. return this._pointerOverSprite;
  22918. };
  22919. // Physics
  22920. Scene.prototype.getPhysicsEngine = function () {
  22921. return this._physicsEngine;
  22922. };
  22923. /**
  22924. * Enables physics to the current scene
  22925. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22926. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22927. * @return {boolean} was the physics engine initialized
  22928. */
  22929. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22930. if (gravity === void 0) { gravity = null; }
  22931. if (this._physicsEngine) {
  22932. return true;
  22933. }
  22934. try {
  22935. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22936. return true;
  22937. }
  22938. catch (e) {
  22939. BABYLON.Tools.Error(e.message);
  22940. return false;
  22941. }
  22942. };
  22943. Scene.prototype.disablePhysicsEngine = function () {
  22944. if (!this._physicsEngine) {
  22945. return;
  22946. }
  22947. this._physicsEngine.dispose();
  22948. this._physicsEngine = null;
  22949. };
  22950. Scene.prototype.isPhysicsEnabled = function () {
  22951. return this._physicsEngine !== undefined;
  22952. };
  22953. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22954. var mesh = compound.parts[0].mesh;
  22955. if (mesh.physicsImpostor) {
  22956. mesh.physicsImpostor.dispose();
  22957. mesh.physicsImpostor = null;
  22958. }
  22959. };
  22960. // Misc.
  22961. Scene.prototype._rebuildGeometries = function () {
  22962. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22963. var geometry = _a[_i];
  22964. geometry._rebuild();
  22965. }
  22966. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22967. var mesh = _c[_b];
  22968. mesh._rebuild();
  22969. }
  22970. if (this.postProcessManager) {
  22971. this.postProcessManager._rebuild();
  22972. }
  22973. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22974. var layer = _e[_d];
  22975. layer._rebuild();
  22976. }
  22977. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22978. var highlightLayer = _g[_f];
  22979. highlightLayer._rebuild();
  22980. }
  22981. if (this._boundingBoxRenderer) {
  22982. this._boundingBoxRenderer._rebuild();
  22983. }
  22984. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22985. var system = _j[_h];
  22986. system.rebuild();
  22987. }
  22988. if (this._postProcessRenderPipelineManager) {
  22989. this._postProcessRenderPipelineManager._rebuild();
  22990. }
  22991. };
  22992. Scene.prototype._rebuildTextures = function () {
  22993. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22994. var texture = _a[_i];
  22995. texture._rebuild();
  22996. }
  22997. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22998. };
  22999. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23000. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23001. if (replace === void 0) { replace = false; }
  23002. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23003. // Dispose existing camera or light in replace mode.
  23004. if (replace) {
  23005. if (this.activeCamera) {
  23006. this.activeCamera.dispose();
  23007. this.activeCamera = null;
  23008. }
  23009. if (this.lights) {
  23010. for (var i = 0; i < this.lights.length; i++) {
  23011. this.lights[i].dispose();
  23012. }
  23013. }
  23014. }
  23015. // Light
  23016. if (this.lights.length === 0) {
  23017. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23018. }
  23019. // Camera
  23020. if (!this.activeCamera) {
  23021. var worldExtends = this.getWorldExtends();
  23022. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23023. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23024. var camera;
  23025. var radius = worldSize.length() * 1.5;
  23026. if (createArcRotateCamera) {
  23027. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23028. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23029. arcRotateCamera.wheelPrecision = 100 / radius;
  23030. camera = arcRotateCamera;
  23031. }
  23032. else {
  23033. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23034. freeCamera.setTarget(worldCenter);
  23035. camera = freeCamera;
  23036. }
  23037. camera.minZ = radius * 0.01;
  23038. camera.maxZ = radius * 1000;
  23039. camera.speed = radius * 0.2;
  23040. this.activeCamera = camera;
  23041. var canvas = this.getEngine().getRenderingCanvas();
  23042. if (attachCameraControls && canvas) {
  23043. camera.attachControl(canvas);
  23044. }
  23045. }
  23046. };
  23047. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23048. if (pbr === void 0) { pbr = false; }
  23049. if (scale === void 0) { scale = 1000; }
  23050. if (blur === void 0) { blur = 0; }
  23051. if (environmentTexture) {
  23052. this.environmentTexture = environmentTexture;
  23053. }
  23054. if (!this.environmentTexture) {
  23055. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23056. return null;
  23057. }
  23058. // Skybox
  23059. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23060. if (pbr) {
  23061. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23062. hdrSkyboxMaterial.backFaceCulling = false;
  23063. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23064. if (hdrSkyboxMaterial.reflectionTexture) {
  23065. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23066. }
  23067. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23068. hdrSkyboxMaterial.disableLighting = true;
  23069. hdrSkyboxMaterial.twoSidedLighting = true;
  23070. hdrSkybox.infiniteDistance = true;
  23071. hdrSkybox.material = hdrSkyboxMaterial;
  23072. }
  23073. else {
  23074. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23075. skyboxMaterial.backFaceCulling = false;
  23076. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23077. if (skyboxMaterial.reflectionTexture) {
  23078. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23079. }
  23080. skyboxMaterial.disableLighting = true;
  23081. hdrSkybox.infiniteDistance = true;
  23082. hdrSkybox.material = skyboxMaterial;
  23083. }
  23084. return hdrSkybox;
  23085. };
  23086. Scene.prototype.createDefaultEnvironment = function (options) {
  23087. if (BABYLON.EnvironmentHelper) {
  23088. return new BABYLON.EnvironmentHelper(options, this);
  23089. }
  23090. return null;
  23091. };
  23092. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23093. if (webVROptions === void 0) { webVROptions = {}; }
  23094. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23095. };
  23096. // Tags
  23097. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23098. if (tagsQuery === undefined) {
  23099. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23100. return list;
  23101. }
  23102. var listByTags = [];
  23103. forEach = forEach || (function (item) { return; });
  23104. for (var i in list) {
  23105. var item = list[i];
  23106. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23107. listByTags.push(item);
  23108. forEach(item);
  23109. }
  23110. }
  23111. return listByTags;
  23112. };
  23113. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23114. return this._getByTags(this.meshes, tagsQuery, forEach);
  23115. };
  23116. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23117. return this._getByTags(this.cameras, tagsQuery, forEach);
  23118. };
  23119. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23120. return this._getByTags(this.lights, tagsQuery, forEach);
  23121. };
  23122. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23123. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23124. };
  23125. /**
  23126. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23127. * This allowed control for front to back rendering or reversly depending of the special needs.
  23128. *
  23129. * @param renderingGroupId The rendering group id corresponding to its index
  23130. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23131. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23132. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23133. */
  23134. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23135. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23136. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23137. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23138. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23139. };
  23140. /**
  23141. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23142. *
  23143. * @param renderingGroupId The rendering group id corresponding to its index
  23144. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23145. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23146. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23147. */
  23148. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23149. if (depth === void 0) { depth = true; }
  23150. if (stencil === void 0) { stencil = true; }
  23151. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23152. };
  23153. /**
  23154. * Will flag all materials as dirty to trigger new shader compilation
  23155. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23156. */
  23157. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23158. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23159. var material = _a[_i];
  23160. if (predicate && !predicate(material)) {
  23161. continue;
  23162. }
  23163. material.markAsDirty(flag);
  23164. }
  23165. };
  23166. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23167. var _this = this;
  23168. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23169. this._activeRequests.push(request);
  23170. request.onCompleteObservable.add(function (request) {
  23171. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23172. });
  23173. return request;
  23174. };
  23175. // Statics
  23176. Scene._FOGMODE_NONE = 0;
  23177. Scene._FOGMODE_EXP = 1;
  23178. Scene._FOGMODE_EXP2 = 2;
  23179. Scene._FOGMODE_LINEAR = 3;
  23180. Scene._uniqueIdCounter = 0;
  23181. Scene.MinDeltaTime = 1.0;
  23182. Scene.MaxDeltaTime = 1000.0;
  23183. /** The distance in pixel that you have to move to prevent some events */
  23184. Scene.DragMovementThreshold = 10; // in pixels
  23185. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23186. Scene.LongPressDelay = 500; // in milliseconds
  23187. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23188. Scene.DoubleClickDelay = 300; // in milliseconds
  23189. /** If you need to check double click without raising a single click at first click, enable this flag */
  23190. Scene.ExclusiveDoubleClickMode = false;
  23191. return Scene;
  23192. }());
  23193. BABYLON.Scene = Scene;
  23194. })(BABYLON || (BABYLON = {}));
  23195. //# sourceMappingURL=babylon.scene.js.map
  23196. var BABYLON;
  23197. (function (BABYLON) {
  23198. var AssetContainer = /** @class */ (function () {
  23199. function AssetContainer(scene) {
  23200. // Objects
  23201. this.cameras = new Array();
  23202. this.lights = new Array();
  23203. this.meshes = new Array();
  23204. this.skeletons = new Array();
  23205. this.particleSystems = new Array();
  23206. this.animations = new Array();
  23207. this.multiMaterials = new Array();
  23208. this.materials = new Array();
  23209. this.morphTargetManagers = new Array();
  23210. this.geometries = new Array();
  23211. this.transformNodes = new Array();
  23212. this.lensFlareSystems = new Array();
  23213. this.shadowGenerators = new Array();
  23214. this.actionManagers = new Array();
  23215. this.sounds = new Array();
  23216. this.scene = scene;
  23217. }
  23218. AssetContainer.prototype.addAllToScene = function () {
  23219. var _this = this;
  23220. this.cameras.forEach(function (o) {
  23221. _this.scene.addCamera(o);
  23222. });
  23223. this.lights.forEach(function (o) {
  23224. _this.scene.addLight(o);
  23225. });
  23226. this.meshes.forEach(function (o) {
  23227. _this.scene.addMesh(o);
  23228. });
  23229. this.skeletons.forEach(function (o) {
  23230. _this.scene.addSkeleton(o);
  23231. });
  23232. this.particleSystems.forEach(function (o) {
  23233. _this.scene.addParticleSystem(o);
  23234. });
  23235. this.animations.forEach(function (o) {
  23236. _this.scene.addAnimation(o);
  23237. });
  23238. this.multiMaterials.forEach(function (o) {
  23239. _this.scene.addMultiMaterial(o);
  23240. });
  23241. this.materials.forEach(function (o) {
  23242. _this.scene.addMaterial(o);
  23243. });
  23244. this.morphTargetManagers.forEach(function (o) {
  23245. _this.scene.addMorphTargetManager(o);
  23246. });
  23247. this.geometries.forEach(function (o) {
  23248. _this.scene.addGeometry(o);
  23249. });
  23250. this.transformNodes.forEach(function (o) {
  23251. _this.scene.addTransformNode(o);
  23252. });
  23253. this.lensFlareSystems.forEach(function (o) {
  23254. _this.scene.addLensFlareSystem(o);
  23255. });
  23256. this.actionManagers.forEach(function (o) {
  23257. _this.scene.addActionManager(o);
  23258. });
  23259. this.sounds.forEach(function (o) {
  23260. o.play();
  23261. o.autoplay = true;
  23262. _this.scene.mainSoundTrack.AddSound(o);
  23263. });
  23264. };
  23265. AssetContainer.prototype.removeAllFromScene = function () {
  23266. var _this = this;
  23267. this.cameras.forEach(function (o) {
  23268. _this.scene.removeCamera(o);
  23269. });
  23270. this.lights.forEach(function (o) {
  23271. _this.scene.removeLight(o);
  23272. });
  23273. this.meshes.forEach(function (o) {
  23274. _this.scene.removeMesh(o);
  23275. });
  23276. this.skeletons.forEach(function (o) {
  23277. _this.scene.removeSkeleton(o);
  23278. });
  23279. this.particleSystems.forEach(function (o) {
  23280. _this.scene.removeParticleSystem(o);
  23281. });
  23282. this.animations.forEach(function (o) {
  23283. _this.scene.removeAnimation(o);
  23284. });
  23285. this.multiMaterials.forEach(function (o) {
  23286. _this.scene.removeMultiMaterial(o);
  23287. });
  23288. this.materials.forEach(function (o) {
  23289. _this.scene.removeMaterial(o);
  23290. });
  23291. this.morphTargetManagers.forEach(function (o) {
  23292. _this.scene.removeMorphTargetManager(o);
  23293. });
  23294. this.geometries.forEach(function (o) {
  23295. _this.scene.removeGeometry(o);
  23296. });
  23297. this.transformNodes.forEach(function (o) {
  23298. _this.scene.removeTransformNode(o);
  23299. });
  23300. this.lensFlareSystems.forEach(function (o) {
  23301. _this.scene.removeLensFlareSystem(o);
  23302. });
  23303. this.actionManagers.forEach(function (o) {
  23304. _this.scene.removeActionManager(o);
  23305. });
  23306. this.sounds.forEach(function (o) {
  23307. o.stop();
  23308. o.autoplay = false;
  23309. _this.scene.mainSoundTrack.RemoveSound(o);
  23310. });
  23311. };
  23312. return AssetContainer;
  23313. }());
  23314. BABYLON.AssetContainer = AssetContainer;
  23315. })(BABYLON || (BABYLON = {}));
  23316. //# sourceMappingURL=babylon.assetContainer.js.map
  23317. var BABYLON;
  23318. (function (BABYLON) {
  23319. var Buffer = /** @class */ (function () {
  23320. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23321. if (instanced === void 0) { instanced = false; }
  23322. if (engine instanceof BABYLON.Mesh) {
  23323. this._engine = engine.getScene().getEngine();
  23324. }
  23325. else {
  23326. this._engine = engine;
  23327. }
  23328. this._updatable = updatable;
  23329. this._data = data;
  23330. this._strideSize = stride;
  23331. if (!postponeInternalCreation) {
  23332. this.create();
  23333. }
  23334. this._instanced = instanced;
  23335. this._instanceDivisor = instanced ? 1 : 0;
  23336. }
  23337. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23338. // a lot of these parameters are ignored as they are overriden by the buffer
  23339. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23340. };
  23341. // Properties
  23342. Buffer.prototype.isUpdatable = function () {
  23343. return this._updatable;
  23344. };
  23345. Buffer.prototype.getData = function () {
  23346. return this._data;
  23347. };
  23348. Buffer.prototype.getBuffer = function () {
  23349. return this._buffer;
  23350. };
  23351. Buffer.prototype.getStrideSize = function () {
  23352. return this._strideSize;
  23353. };
  23354. Buffer.prototype.getIsInstanced = function () {
  23355. return this._instanced;
  23356. };
  23357. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23358. get: function () {
  23359. return this._instanceDivisor;
  23360. },
  23361. set: function (value) {
  23362. this._instanceDivisor = value;
  23363. if (value == 0) {
  23364. this._instanced = false;
  23365. }
  23366. else {
  23367. this._instanced = true;
  23368. }
  23369. },
  23370. enumerable: true,
  23371. configurable: true
  23372. });
  23373. // Methods
  23374. Buffer.prototype.create = function (data) {
  23375. if (data === void 0) { data = null; }
  23376. if (!data && this._buffer) {
  23377. return; // nothing to do
  23378. }
  23379. data = data || this._data;
  23380. if (!data) {
  23381. return;
  23382. }
  23383. if (!this._buffer) {
  23384. if (this._updatable) {
  23385. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23386. this._data = data;
  23387. }
  23388. else {
  23389. this._buffer = this._engine.createVertexBuffer(data);
  23390. }
  23391. }
  23392. else if (this._updatable) {
  23393. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23394. this._data = data;
  23395. }
  23396. };
  23397. Buffer.prototype._rebuild = function () {
  23398. this._buffer = null;
  23399. this.create(this._data);
  23400. };
  23401. Buffer.prototype.update = function (data) {
  23402. this.create(data);
  23403. };
  23404. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23405. if (!this._buffer) {
  23406. return;
  23407. }
  23408. if (this._updatable) {
  23409. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23410. this._data = null;
  23411. }
  23412. };
  23413. Buffer.prototype.dispose = function () {
  23414. if (!this._buffer) {
  23415. return;
  23416. }
  23417. if (this._engine._releaseBuffer(this._buffer)) {
  23418. this._buffer = null;
  23419. }
  23420. };
  23421. return Buffer;
  23422. }());
  23423. BABYLON.Buffer = Buffer;
  23424. })(BABYLON || (BABYLON = {}));
  23425. //# sourceMappingURL=babylon.buffer.js.map
  23426. var BABYLON;
  23427. (function (BABYLON) {
  23428. var VertexBuffer = /** @class */ (function () {
  23429. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23430. if (!stride) {
  23431. // Deduce stride from kind
  23432. switch (kind) {
  23433. case VertexBuffer.PositionKind:
  23434. stride = 3;
  23435. break;
  23436. case VertexBuffer.NormalKind:
  23437. stride = 3;
  23438. break;
  23439. case VertexBuffer.UVKind:
  23440. case VertexBuffer.UV2Kind:
  23441. case VertexBuffer.UV3Kind:
  23442. case VertexBuffer.UV4Kind:
  23443. case VertexBuffer.UV5Kind:
  23444. case VertexBuffer.UV6Kind:
  23445. stride = 2;
  23446. break;
  23447. case VertexBuffer.TangentKind:
  23448. case VertexBuffer.ColorKind:
  23449. stride = 4;
  23450. break;
  23451. case VertexBuffer.MatricesIndicesKind:
  23452. case VertexBuffer.MatricesIndicesExtraKind:
  23453. stride = 4;
  23454. break;
  23455. case VertexBuffer.MatricesWeightsKind:
  23456. case VertexBuffer.MatricesWeightsExtraKind:
  23457. default:
  23458. stride = 4;
  23459. break;
  23460. }
  23461. }
  23462. if (data instanceof BABYLON.Buffer) {
  23463. if (!stride) {
  23464. stride = data.getStrideSize();
  23465. }
  23466. this._buffer = data;
  23467. this._ownsBuffer = false;
  23468. }
  23469. else {
  23470. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23471. this._ownsBuffer = true;
  23472. }
  23473. this._stride = stride;
  23474. this._offset = offset ? offset : 0;
  23475. this._size = size ? size : stride;
  23476. this._kind = kind;
  23477. }
  23478. VertexBuffer.prototype._rebuild = function () {
  23479. if (!this._buffer) {
  23480. return;
  23481. }
  23482. this._buffer._rebuild();
  23483. };
  23484. /**
  23485. * Returns the kind of the VertexBuffer (string).
  23486. */
  23487. VertexBuffer.prototype.getKind = function () {
  23488. return this._kind;
  23489. };
  23490. // Properties
  23491. /**
  23492. * Boolean : is the VertexBuffer updatable ?
  23493. */
  23494. VertexBuffer.prototype.isUpdatable = function () {
  23495. return this._buffer.isUpdatable();
  23496. };
  23497. /**
  23498. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23499. */
  23500. VertexBuffer.prototype.getData = function () {
  23501. return this._buffer.getData();
  23502. };
  23503. /**
  23504. * Returns the WebGLBuffer associated to the VertexBuffer.
  23505. */
  23506. VertexBuffer.prototype.getBuffer = function () {
  23507. return this._buffer.getBuffer();
  23508. };
  23509. /**
  23510. * Returns the stride of the VertexBuffer (integer).
  23511. */
  23512. VertexBuffer.prototype.getStrideSize = function () {
  23513. return this._stride;
  23514. };
  23515. /**
  23516. * Returns the offset (integer).
  23517. */
  23518. VertexBuffer.prototype.getOffset = function () {
  23519. return this._offset;
  23520. };
  23521. /**
  23522. * Returns the VertexBuffer total size (integer).
  23523. */
  23524. VertexBuffer.prototype.getSize = function () {
  23525. return this._size;
  23526. };
  23527. /**
  23528. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23529. */
  23530. VertexBuffer.prototype.getIsInstanced = function () {
  23531. return this._buffer.getIsInstanced();
  23532. };
  23533. /**
  23534. * Returns the instancing divisor, zero for non-instanced (integer).
  23535. */
  23536. VertexBuffer.prototype.getInstanceDivisor = function () {
  23537. return this._buffer.instanceDivisor;
  23538. };
  23539. // Methods
  23540. /**
  23541. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23542. * Returns the created WebGLBuffer.
  23543. */
  23544. VertexBuffer.prototype.create = function (data) {
  23545. return this._buffer.create(data);
  23546. };
  23547. /**
  23548. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23549. * Returns the updated WebGLBuffer.
  23550. */
  23551. VertexBuffer.prototype.update = function (data) {
  23552. return this._buffer.update(data);
  23553. };
  23554. /**
  23555. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23556. * Returns the directly updated WebGLBuffer.
  23557. */
  23558. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23559. return this._buffer.updateDirectly(data, offset);
  23560. };
  23561. /**
  23562. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23563. */
  23564. VertexBuffer.prototype.dispose = function () {
  23565. if (this._ownsBuffer) {
  23566. this._buffer.dispose();
  23567. }
  23568. };
  23569. Object.defineProperty(VertexBuffer, "PositionKind", {
  23570. get: function () {
  23571. return VertexBuffer._PositionKind;
  23572. },
  23573. enumerable: true,
  23574. configurable: true
  23575. });
  23576. Object.defineProperty(VertexBuffer, "NormalKind", {
  23577. get: function () {
  23578. return VertexBuffer._NormalKind;
  23579. },
  23580. enumerable: true,
  23581. configurable: true
  23582. });
  23583. Object.defineProperty(VertexBuffer, "TangentKind", {
  23584. get: function () {
  23585. return VertexBuffer._TangentKind;
  23586. },
  23587. enumerable: true,
  23588. configurable: true
  23589. });
  23590. Object.defineProperty(VertexBuffer, "UVKind", {
  23591. get: function () {
  23592. return VertexBuffer._UVKind;
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23598. get: function () {
  23599. return VertexBuffer._UV2Kind;
  23600. },
  23601. enumerable: true,
  23602. configurable: true
  23603. });
  23604. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23605. get: function () {
  23606. return VertexBuffer._UV3Kind;
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23612. get: function () {
  23613. return VertexBuffer._UV4Kind;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23619. get: function () {
  23620. return VertexBuffer._UV5Kind;
  23621. },
  23622. enumerable: true,
  23623. configurable: true
  23624. });
  23625. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23626. get: function () {
  23627. return VertexBuffer._UV6Kind;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. Object.defineProperty(VertexBuffer, "ColorKind", {
  23633. get: function () {
  23634. return VertexBuffer._ColorKind;
  23635. },
  23636. enumerable: true,
  23637. configurable: true
  23638. });
  23639. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23640. get: function () {
  23641. return VertexBuffer._MatricesIndicesKind;
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23647. get: function () {
  23648. return VertexBuffer._MatricesWeightsKind;
  23649. },
  23650. enumerable: true,
  23651. configurable: true
  23652. });
  23653. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23654. get: function () {
  23655. return VertexBuffer._MatricesIndicesExtraKind;
  23656. },
  23657. enumerable: true,
  23658. configurable: true
  23659. });
  23660. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23661. get: function () {
  23662. return VertexBuffer._MatricesWeightsExtraKind;
  23663. },
  23664. enumerable: true,
  23665. configurable: true
  23666. });
  23667. // Enums
  23668. VertexBuffer._PositionKind = "position";
  23669. VertexBuffer._NormalKind = "normal";
  23670. VertexBuffer._TangentKind = "tangent";
  23671. VertexBuffer._UVKind = "uv";
  23672. VertexBuffer._UV2Kind = "uv2";
  23673. VertexBuffer._UV3Kind = "uv3";
  23674. VertexBuffer._UV4Kind = "uv4";
  23675. VertexBuffer._UV5Kind = "uv5";
  23676. VertexBuffer._UV6Kind = "uv6";
  23677. VertexBuffer._ColorKind = "color";
  23678. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23679. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23680. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23681. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23682. return VertexBuffer;
  23683. }());
  23684. BABYLON.VertexBuffer = VertexBuffer;
  23685. })(BABYLON || (BABYLON = {}));
  23686. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23687. var BABYLON;
  23688. (function (BABYLON) {
  23689. var InternalTexture = /** @class */ (function () {
  23690. function InternalTexture(engine, dataSource) {
  23691. this.onLoadedObservable = new BABYLON.Observable();
  23692. // Private
  23693. this._initialSlot = -1;
  23694. this._designatedSlot = -1;
  23695. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23696. this._references = 1;
  23697. this._engine = engine;
  23698. this._dataSource = dataSource;
  23699. this._webGLTexture = engine._createTexture();
  23700. }
  23701. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23702. get: function () {
  23703. return this._dataSource;
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. InternalTexture.prototype.incrementReferences = function () {
  23709. this._references++;
  23710. };
  23711. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23712. if (depth === void 0) { depth = 1; }
  23713. this.width = width;
  23714. this.height = height;
  23715. this.depth = depth;
  23716. this.baseWidth = width;
  23717. this.baseHeight = height;
  23718. this.baseDepth = depth;
  23719. this._size = width * height * depth;
  23720. };
  23721. InternalTexture.prototype._rebuild = function () {
  23722. var _this = this;
  23723. var proxy;
  23724. this.isReady = false;
  23725. this._cachedCoordinatesMode = null;
  23726. this._cachedWrapU = null;
  23727. this._cachedWrapV = null;
  23728. this._cachedAnisotropicFilteringLevel = null;
  23729. switch (this._dataSource) {
  23730. case InternalTexture.DATASOURCE_TEMP:
  23731. return;
  23732. case InternalTexture.DATASOURCE_URL:
  23733. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23734. _this.isReady = true;
  23735. }, null, this._buffer, undefined, this.format);
  23736. proxy._swapAndDie(this);
  23737. return;
  23738. case InternalTexture.DATASOURCE_RAW:
  23739. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23740. proxy._swapAndDie(this);
  23741. this.isReady = true;
  23742. return;
  23743. case InternalTexture.DATASOURCE_RAW3D:
  23744. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23745. proxy._swapAndDie(this);
  23746. this.isReady = true;
  23747. return;
  23748. case InternalTexture.DATASOURCE_DYNAMIC:
  23749. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23750. proxy._swapAndDie(this);
  23751. // The engine will make sure to update content so no need to flag it as isReady = true
  23752. return;
  23753. case InternalTexture.DATASOURCE_RENDERTARGET:
  23754. var options = new BABYLON.RenderTargetCreationOptions();
  23755. options.generateDepthBuffer = this._generateDepthBuffer;
  23756. options.generateMipMaps = this.generateMipMaps;
  23757. options.generateStencilBuffer = this._generateStencilBuffer;
  23758. options.samplingMode = this.samplingMode;
  23759. options.type = this.type;
  23760. if (this.isCube) {
  23761. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23762. }
  23763. else {
  23764. var size = {
  23765. width: this.width,
  23766. height: this.height
  23767. };
  23768. proxy = this._engine.createRenderTargetTexture(size, options);
  23769. }
  23770. proxy._swapAndDie(this);
  23771. this.isReady = true;
  23772. return;
  23773. case InternalTexture.DATASOURCE_CUBE:
  23774. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23775. _this.isReady = true;
  23776. }, null, this.format, this._extension);
  23777. proxy._swapAndDie(this);
  23778. return;
  23779. case InternalTexture.DATASOURCE_CUBERAW:
  23780. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23781. proxy._swapAndDie(this);
  23782. this.isReady = true;
  23783. return;
  23784. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23785. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23786. if (proxy) {
  23787. proxy._swapAndDie(_this);
  23788. }
  23789. _this.isReady = true;
  23790. }, null, this.format, this._extension);
  23791. return;
  23792. }
  23793. };
  23794. InternalTexture.prototype._swapAndDie = function (target) {
  23795. target._webGLTexture = this._webGLTexture;
  23796. if (this._framebuffer) {
  23797. target._framebuffer = this._framebuffer;
  23798. }
  23799. if (this._depthStencilBuffer) {
  23800. target._depthStencilBuffer = this._depthStencilBuffer;
  23801. }
  23802. if (this._lodTextureHigh) {
  23803. if (target._lodTextureHigh) {
  23804. target._lodTextureHigh.dispose();
  23805. }
  23806. target._lodTextureHigh = this._lodTextureHigh;
  23807. }
  23808. if (this._lodTextureMid) {
  23809. if (target._lodTextureMid) {
  23810. target._lodTextureMid.dispose();
  23811. }
  23812. target._lodTextureMid = this._lodTextureMid;
  23813. }
  23814. if (this._lodTextureLow) {
  23815. if (target._lodTextureLow) {
  23816. target._lodTextureLow.dispose();
  23817. }
  23818. target._lodTextureLow = this._lodTextureLow;
  23819. }
  23820. var cache = this._engine.getLoadedTexturesCache();
  23821. var index = cache.indexOf(this);
  23822. if (index !== -1) {
  23823. cache.splice(index, 1);
  23824. }
  23825. };
  23826. InternalTexture.prototype.dispose = function () {
  23827. if (!this._webGLTexture) {
  23828. return;
  23829. }
  23830. this._references--;
  23831. if (this._references === 0) {
  23832. this._engine._releaseTexture(this);
  23833. this._webGLTexture = null;
  23834. }
  23835. };
  23836. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23837. InternalTexture.DATASOURCE_URL = 1;
  23838. InternalTexture.DATASOURCE_TEMP = 2;
  23839. InternalTexture.DATASOURCE_RAW = 3;
  23840. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23841. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23842. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23843. InternalTexture.DATASOURCE_CUBE = 7;
  23844. InternalTexture.DATASOURCE_CUBERAW = 8;
  23845. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23846. InternalTexture.DATASOURCE_RAW3D = 10;
  23847. return InternalTexture;
  23848. }());
  23849. BABYLON.InternalTexture = InternalTexture;
  23850. })(BABYLON || (BABYLON = {}));
  23851. //# sourceMappingURL=babylon.internalTexture.js.map
  23852. var BABYLON;
  23853. (function (BABYLON) {
  23854. var BaseTexture = /** @class */ (function () {
  23855. function BaseTexture(scene) {
  23856. this._hasAlpha = false;
  23857. this.getAlphaFromRGB = false;
  23858. this.level = 1;
  23859. this.coordinatesIndex = 0;
  23860. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23861. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23862. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23863. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23864. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23865. this.isCube = false;
  23866. this.is3D = false;
  23867. this.gammaSpace = true;
  23868. this.invertZ = false;
  23869. this.lodLevelInAlpha = false;
  23870. this.lodGenerationOffset = 0.0;
  23871. this.lodGenerationScale = 0.8;
  23872. this.isRenderTarget = false;
  23873. this.animations = new Array();
  23874. /**
  23875. * An event triggered when the texture is disposed.
  23876. * @type {BABYLON.Observable}
  23877. */
  23878. this.onDisposeObservable = new BABYLON.Observable();
  23879. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23880. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23881. if (this._scene) {
  23882. this._scene.textures.push(this);
  23883. }
  23884. this._uid = null;
  23885. }
  23886. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23887. get: function () {
  23888. return this._hasAlpha;
  23889. },
  23890. set: function (value) {
  23891. if (this._hasAlpha === value) {
  23892. return;
  23893. }
  23894. this._hasAlpha = value;
  23895. if (this._scene) {
  23896. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23897. }
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23903. get: function () {
  23904. return this._coordinatesMode;
  23905. },
  23906. set: function (value) {
  23907. if (this._coordinatesMode === value) {
  23908. return;
  23909. }
  23910. this._coordinatesMode = value;
  23911. if (this._scene) {
  23912. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23913. }
  23914. },
  23915. enumerable: true,
  23916. configurable: true
  23917. });
  23918. Object.defineProperty(BaseTexture.prototype, "uid", {
  23919. get: function () {
  23920. if (!this._uid) {
  23921. this._uid = BABYLON.Tools.RandomId();
  23922. }
  23923. return this._uid;
  23924. },
  23925. enumerable: true,
  23926. configurable: true
  23927. });
  23928. BaseTexture.prototype.toString = function () {
  23929. return this.name;
  23930. };
  23931. BaseTexture.prototype.getClassName = function () {
  23932. return "BaseTexture";
  23933. };
  23934. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23935. set: function (callback) {
  23936. if (this._onDisposeObserver) {
  23937. this.onDisposeObservable.remove(this._onDisposeObserver);
  23938. }
  23939. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23940. },
  23941. enumerable: true,
  23942. configurable: true
  23943. });
  23944. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23945. get: function () {
  23946. return true;
  23947. },
  23948. enumerable: true,
  23949. configurable: true
  23950. });
  23951. BaseTexture.prototype.getScene = function () {
  23952. return this._scene;
  23953. };
  23954. BaseTexture.prototype.getTextureMatrix = function () {
  23955. return BABYLON.Matrix.IdentityReadOnly;
  23956. };
  23957. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23958. return BABYLON.Matrix.IdentityReadOnly;
  23959. };
  23960. BaseTexture.prototype.getInternalTexture = function () {
  23961. return this._texture;
  23962. };
  23963. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23964. return !this.isBlocking || this.isReady();
  23965. };
  23966. BaseTexture.prototype.isReady = function () {
  23967. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23968. this.delayLoad();
  23969. return false;
  23970. }
  23971. if (this._texture) {
  23972. return this._texture.isReady;
  23973. }
  23974. return false;
  23975. };
  23976. BaseTexture.prototype.getSize = function () {
  23977. if (this._texture && this._texture.width) {
  23978. return new BABYLON.Size(this._texture.width, this._texture.height);
  23979. }
  23980. if (this._texture && this._texture._size) {
  23981. return new BABYLON.Size(this._texture._size, this._texture._size);
  23982. }
  23983. return BABYLON.Size.Zero();
  23984. };
  23985. BaseTexture.prototype.getBaseSize = function () {
  23986. if (!this.isReady() || !this._texture)
  23987. return BABYLON.Size.Zero();
  23988. if (this._texture._size) {
  23989. return new BABYLON.Size(this._texture._size, this._texture._size);
  23990. }
  23991. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23992. };
  23993. BaseTexture.prototype.scale = function (ratio) {
  23994. };
  23995. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23996. get: function () {
  23997. return false;
  23998. },
  23999. enumerable: true,
  24000. configurable: true
  24001. });
  24002. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24003. if (!this._scene) {
  24004. return null;
  24005. }
  24006. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24007. for (var index = 0; index < texturesCache.length; index++) {
  24008. var texturesCacheEntry = texturesCache[index];
  24009. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24010. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24011. texturesCacheEntry.incrementReferences();
  24012. return texturesCacheEntry;
  24013. }
  24014. }
  24015. }
  24016. return null;
  24017. };
  24018. BaseTexture.prototype._rebuild = function () {
  24019. };
  24020. BaseTexture.prototype.delayLoad = function () {
  24021. };
  24022. BaseTexture.prototype.clone = function () {
  24023. return null;
  24024. };
  24025. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24026. get: function () {
  24027. if (!this._texture) {
  24028. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24029. }
  24030. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24031. },
  24032. enumerable: true,
  24033. configurable: true
  24034. });
  24035. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24036. get: function () {
  24037. if (!this._texture) {
  24038. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24039. }
  24040. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24041. },
  24042. enumerable: true,
  24043. configurable: true
  24044. });
  24045. BaseTexture.prototype.readPixels = function (faceIndex) {
  24046. if (faceIndex === void 0) { faceIndex = 0; }
  24047. if (!this._texture) {
  24048. return null;
  24049. }
  24050. var size = this.getSize();
  24051. var scene = this.getScene();
  24052. if (!scene) {
  24053. return null;
  24054. }
  24055. var engine = scene.getEngine();
  24056. if (this._texture.isCube) {
  24057. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24058. }
  24059. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24060. };
  24061. BaseTexture.prototype.releaseInternalTexture = function () {
  24062. if (this._texture) {
  24063. this._texture.dispose();
  24064. this._texture = null;
  24065. }
  24066. };
  24067. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24068. get: function () {
  24069. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24070. return null;
  24071. }
  24072. if (!this._texture._sphericalPolynomial) {
  24073. this._texture._sphericalPolynomial =
  24074. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24075. }
  24076. return this._texture._sphericalPolynomial;
  24077. },
  24078. set: function (value) {
  24079. if (this._texture) {
  24080. this._texture._sphericalPolynomial = value;
  24081. }
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24087. get: function () {
  24088. if (this._texture) {
  24089. return this._texture._lodTextureHigh;
  24090. }
  24091. return null;
  24092. },
  24093. enumerable: true,
  24094. configurable: true
  24095. });
  24096. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24097. get: function () {
  24098. if (this._texture) {
  24099. return this._texture._lodTextureMid;
  24100. }
  24101. return null;
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24107. get: function () {
  24108. if (this._texture) {
  24109. return this._texture._lodTextureLow;
  24110. }
  24111. return null;
  24112. },
  24113. enumerable: true,
  24114. configurable: true
  24115. });
  24116. BaseTexture.prototype.dispose = function () {
  24117. if (!this._scene) {
  24118. return;
  24119. }
  24120. // Animations
  24121. this._scene.stopAnimation(this);
  24122. // Remove from scene
  24123. this._scene._removePendingData(this);
  24124. var index = this._scene.textures.indexOf(this);
  24125. if (index >= 0) {
  24126. this._scene.textures.splice(index, 1);
  24127. }
  24128. if (this._texture === undefined) {
  24129. return;
  24130. }
  24131. // Release
  24132. this.releaseInternalTexture();
  24133. // Callback
  24134. this.onDisposeObservable.notifyObservers(this);
  24135. this.onDisposeObservable.clear();
  24136. };
  24137. BaseTexture.prototype.serialize = function () {
  24138. if (!this.name) {
  24139. return null;
  24140. }
  24141. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24142. // Animations
  24143. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24144. return serializationObject;
  24145. };
  24146. BaseTexture.WhenAllReady = function (textures, callback) {
  24147. var numRemaining = textures.length;
  24148. if (numRemaining === 0) {
  24149. callback();
  24150. return;
  24151. }
  24152. var _loop_1 = function () {
  24153. texture = textures[i];
  24154. if (texture.isReady()) {
  24155. if (--numRemaining === 0) {
  24156. callback();
  24157. }
  24158. }
  24159. else {
  24160. onLoadObservable = texture.onLoadObservable;
  24161. var onLoadCallback_1 = function () {
  24162. onLoadObservable.removeCallback(onLoadCallback_1);
  24163. if (--numRemaining === 0) {
  24164. callback();
  24165. }
  24166. };
  24167. onLoadObservable.add(onLoadCallback_1);
  24168. }
  24169. };
  24170. var texture, onLoadObservable;
  24171. for (var i = 0; i < textures.length; i++) {
  24172. _loop_1();
  24173. }
  24174. };
  24175. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24176. __decorate([
  24177. BABYLON.serialize()
  24178. ], BaseTexture.prototype, "name", void 0);
  24179. __decorate([
  24180. BABYLON.serialize("hasAlpha")
  24181. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24182. __decorate([
  24183. BABYLON.serialize()
  24184. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24185. __decorate([
  24186. BABYLON.serialize()
  24187. ], BaseTexture.prototype, "level", void 0);
  24188. __decorate([
  24189. BABYLON.serialize()
  24190. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24191. __decorate([
  24192. BABYLON.serialize("coordinatesMode")
  24193. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24194. __decorate([
  24195. BABYLON.serialize()
  24196. ], BaseTexture.prototype, "wrapU", void 0);
  24197. __decorate([
  24198. BABYLON.serialize()
  24199. ], BaseTexture.prototype, "wrapV", void 0);
  24200. __decorate([
  24201. BABYLON.serialize()
  24202. ], BaseTexture.prototype, "wrapR", void 0);
  24203. __decorate([
  24204. BABYLON.serialize()
  24205. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24206. __decorate([
  24207. BABYLON.serialize()
  24208. ], BaseTexture.prototype, "isCube", void 0);
  24209. __decorate([
  24210. BABYLON.serialize()
  24211. ], BaseTexture.prototype, "is3D", void 0);
  24212. __decorate([
  24213. BABYLON.serialize()
  24214. ], BaseTexture.prototype, "gammaSpace", void 0);
  24215. __decorate([
  24216. BABYLON.serialize()
  24217. ], BaseTexture.prototype, "invertZ", void 0);
  24218. __decorate([
  24219. BABYLON.serialize()
  24220. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24221. __decorate([
  24222. BABYLON.serialize()
  24223. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24224. __decorate([
  24225. BABYLON.serialize()
  24226. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24227. __decorate([
  24228. BABYLON.serialize()
  24229. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24230. return BaseTexture;
  24231. }());
  24232. BABYLON.BaseTexture = BaseTexture;
  24233. })(BABYLON || (BABYLON = {}));
  24234. //# sourceMappingURL=babylon.baseTexture.js.map
  24235. var BABYLON;
  24236. (function (BABYLON) {
  24237. var Texture = /** @class */ (function (_super) {
  24238. __extends(Texture, _super);
  24239. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24240. if (noMipmap === void 0) { noMipmap = false; }
  24241. if (invertY === void 0) { invertY = true; }
  24242. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24243. if (onLoad === void 0) { onLoad = null; }
  24244. if (onError === void 0) { onError = null; }
  24245. if (buffer === void 0) { buffer = null; }
  24246. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24247. var _this = _super.call(this, scene) || this;
  24248. _this.uOffset = 0;
  24249. _this.vOffset = 0;
  24250. _this.uScale = 1.0;
  24251. _this.vScale = 1.0;
  24252. _this.uAng = 0;
  24253. _this.vAng = 0;
  24254. _this.wAng = 0;
  24255. _this._isBlocking = true;
  24256. _this.name = url || "";
  24257. _this.url = url;
  24258. _this._noMipmap = noMipmap;
  24259. _this._invertY = invertY;
  24260. _this._samplingMode = samplingMode;
  24261. _this._buffer = buffer;
  24262. _this._deleteBuffer = deleteBuffer;
  24263. if (format) {
  24264. _this._format = format;
  24265. }
  24266. scene = _this.getScene();
  24267. if (!scene) {
  24268. return _this;
  24269. }
  24270. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24271. var load = function () {
  24272. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24273. _this.onLoadObservable.notifyObservers(_this);
  24274. }
  24275. if (onLoad) {
  24276. onLoad();
  24277. }
  24278. if (!_this.isBlocking && scene) {
  24279. scene.resetCachedMaterial();
  24280. }
  24281. };
  24282. if (!_this.url) {
  24283. _this._delayedOnLoad = load;
  24284. _this._delayedOnError = onError;
  24285. return _this;
  24286. }
  24287. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24288. if (!_this._texture) {
  24289. if (!scene.useDelayedTextureLoading) {
  24290. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24291. if (deleteBuffer) {
  24292. delete _this._buffer;
  24293. }
  24294. }
  24295. else {
  24296. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24297. _this._delayedOnLoad = load;
  24298. _this._delayedOnError = onError;
  24299. }
  24300. }
  24301. else {
  24302. if (_this._texture.isReady) {
  24303. BABYLON.Tools.SetImmediate(function () { return load(); });
  24304. }
  24305. else {
  24306. _this._texture.onLoadedObservable.add(load);
  24307. }
  24308. }
  24309. return _this;
  24310. }
  24311. Object.defineProperty(Texture.prototype, "noMipmap", {
  24312. get: function () {
  24313. return this._noMipmap;
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(Texture.prototype, "isBlocking", {
  24319. get: function () {
  24320. return this._isBlocking;
  24321. },
  24322. set: function (value) {
  24323. this._isBlocking = value;
  24324. },
  24325. enumerable: true,
  24326. configurable: true
  24327. });
  24328. Object.defineProperty(Texture.prototype, "samplingMode", {
  24329. get: function () {
  24330. return this._samplingMode;
  24331. },
  24332. enumerable: true,
  24333. configurable: true
  24334. });
  24335. Texture.prototype.updateURL = function (url) {
  24336. this.url = url;
  24337. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24338. this.delayLoad();
  24339. };
  24340. Texture.prototype.delayLoad = function () {
  24341. var _this = this;
  24342. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24343. return;
  24344. }
  24345. var scene = this.getScene();
  24346. if (!scene) {
  24347. return;
  24348. }
  24349. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24350. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24351. if (!this._texture) {
  24352. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24353. if (this._deleteBuffer) {
  24354. delete this._buffer;
  24355. }
  24356. }
  24357. else {
  24358. if (this._texture.isReady) {
  24359. BABYLON.Tools.SetImmediate(function () {
  24360. if (!_this._delayedOnLoad) {
  24361. return;
  24362. }
  24363. _this._delayedOnLoad();
  24364. });
  24365. }
  24366. else {
  24367. if (this._delayedOnLoad) {
  24368. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24369. }
  24370. }
  24371. }
  24372. };
  24373. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24374. if (!this._texture) {
  24375. return;
  24376. }
  24377. var scene = this.getScene();
  24378. if (!scene) {
  24379. return;
  24380. }
  24381. this._samplingMode = samplingMode;
  24382. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24383. };
  24384. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24385. x *= this.uScale;
  24386. y *= this.vScale;
  24387. x -= 0.5 * this.uScale;
  24388. y -= 0.5 * this.vScale;
  24389. z -= 0.5;
  24390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24391. t.x += 0.5 * this.uScale + this.uOffset;
  24392. t.y += 0.5 * this.vScale + this.vOffset;
  24393. t.z += 0.5;
  24394. };
  24395. Texture.prototype.getTextureMatrix = function () {
  24396. var _this = this;
  24397. if (this.uOffset === this._cachedUOffset &&
  24398. this.vOffset === this._cachedVOffset &&
  24399. this.uScale === this._cachedUScale &&
  24400. this.vScale === this._cachedVScale &&
  24401. this.uAng === this._cachedUAng &&
  24402. this.vAng === this._cachedVAng &&
  24403. this.wAng === this._cachedWAng) {
  24404. return this._cachedTextureMatrix;
  24405. }
  24406. this._cachedUOffset = this.uOffset;
  24407. this._cachedVOffset = this.vOffset;
  24408. this._cachedUScale = this.uScale;
  24409. this._cachedVScale = this.vScale;
  24410. this._cachedUAng = this.uAng;
  24411. this._cachedVAng = this.vAng;
  24412. this._cachedWAng = this.wAng;
  24413. if (!this._cachedTextureMatrix) {
  24414. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24415. this._rowGenerationMatrix = new BABYLON.Matrix();
  24416. this._t0 = BABYLON.Vector3.Zero();
  24417. this._t1 = BABYLON.Vector3.Zero();
  24418. this._t2 = BABYLON.Vector3.Zero();
  24419. }
  24420. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24421. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24422. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24423. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24424. this._t1.subtractInPlace(this._t0);
  24425. this._t2.subtractInPlace(this._t0);
  24426. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24427. this._cachedTextureMatrix.m[0] = this._t1.x;
  24428. this._cachedTextureMatrix.m[1] = this._t1.y;
  24429. this._cachedTextureMatrix.m[2] = this._t1.z;
  24430. this._cachedTextureMatrix.m[4] = this._t2.x;
  24431. this._cachedTextureMatrix.m[5] = this._t2.y;
  24432. this._cachedTextureMatrix.m[6] = this._t2.z;
  24433. this._cachedTextureMatrix.m[8] = this._t0.x;
  24434. this._cachedTextureMatrix.m[9] = this._t0.y;
  24435. this._cachedTextureMatrix.m[10] = this._t0.z;
  24436. var scene = this.getScene();
  24437. if (!scene) {
  24438. return this._cachedTextureMatrix;
  24439. }
  24440. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24441. return mat.hasTexture(_this);
  24442. });
  24443. return this._cachedTextureMatrix;
  24444. };
  24445. Texture.prototype.getReflectionTextureMatrix = function () {
  24446. var _this = this;
  24447. var scene = this.getScene();
  24448. if (!scene) {
  24449. return this._cachedTextureMatrix;
  24450. }
  24451. if (this.uOffset === this._cachedUOffset &&
  24452. this.vOffset === this._cachedVOffset &&
  24453. this.uScale === this._cachedUScale &&
  24454. this.vScale === this._cachedVScale &&
  24455. this.coordinatesMode === this._cachedCoordinatesMode) {
  24456. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24457. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24458. return this._cachedTextureMatrix;
  24459. }
  24460. }
  24461. else {
  24462. return this._cachedTextureMatrix;
  24463. }
  24464. }
  24465. if (!this._cachedTextureMatrix) {
  24466. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24467. }
  24468. if (!this._projectionModeMatrix) {
  24469. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24470. }
  24471. this._cachedUOffset = this.uOffset;
  24472. this._cachedVOffset = this.vOffset;
  24473. this._cachedUScale = this.uScale;
  24474. this._cachedVScale = this.vScale;
  24475. this._cachedCoordinatesMode = this.coordinatesMode;
  24476. switch (this.coordinatesMode) {
  24477. case Texture.PLANAR_MODE:
  24478. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24479. this._cachedTextureMatrix[0] = this.uScale;
  24480. this._cachedTextureMatrix[5] = this.vScale;
  24481. this._cachedTextureMatrix[12] = this.uOffset;
  24482. this._cachedTextureMatrix[13] = this.vOffset;
  24483. break;
  24484. case Texture.PROJECTION_MODE:
  24485. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24486. this._projectionModeMatrix.m[0] = 0.5;
  24487. this._projectionModeMatrix.m[5] = -0.5;
  24488. this._projectionModeMatrix.m[10] = 0.0;
  24489. this._projectionModeMatrix.m[12] = 0.5;
  24490. this._projectionModeMatrix.m[13] = 0.5;
  24491. this._projectionModeMatrix.m[14] = 1.0;
  24492. this._projectionModeMatrix.m[15] = 1.0;
  24493. var projectionMatrix = scene.getProjectionMatrix();
  24494. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24495. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24496. break;
  24497. default:
  24498. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24499. break;
  24500. }
  24501. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24502. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24503. });
  24504. return this._cachedTextureMatrix;
  24505. };
  24506. Texture.prototype.clone = function () {
  24507. var _this = this;
  24508. return BABYLON.SerializationHelper.Clone(function () {
  24509. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24510. }, this);
  24511. };
  24512. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24513. get: function () {
  24514. if (!this._onLoadObservable) {
  24515. this._onLoadObservable = new BABYLON.Observable();
  24516. }
  24517. return this._onLoadObservable;
  24518. },
  24519. enumerable: true,
  24520. configurable: true
  24521. });
  24522. Texture.prototype.serialize = function () {
  24523. var serializationObject = _super.prototype.serialize.call(this);
  24524. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24525. serializationObject.base64String = this._buffer;
  24526. serializationObject.name = serializationObject.name.replace("data:", "");
  24527. }
  24528. return serializationObject;
  24529. };
  24530. Texture.prototype.getClassName = function () {
  24531. return "Texture";
  24532. };
  24533. Texture.prototype.dispose = function () {
  24534. _super.prototype.dispose.call(this);
  24535. if (this.onLoadObservable) {
  24536. this.onLoadObservable.clear();
  24537. this._onLoadObservable = null;
  24538. }
  24539. this._delayedOnLoad = null;
  24540. this._delayedOnError = null;
  24541. };
  24542. // Statics
  24543. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24544. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24545. if (onLoad === void 0) { onLoad = null; }
  24546. if (onError === void 0) { onError = null; }
  24547. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24548. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24549. };
  24550. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24551. if (parsedTexture.customType) {
  24552. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24553. // Update Sampling Mode
  24554. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24555. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24556. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24557. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24558. }
  24559. }
  24560. return parsedCustomTexture;
  24561. }
  24562. if (parsedTexture.isCube) {
  24563. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24564. }
  24565. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24566. return null;
  24567. }
  24568. var texture = BABYLON.SerializationHelper.Parse(function () {
  24569. var generateMipMaps = true;
  24570. if (parsedTexture.noMipmap) {
  24571. generateMipMaps = false;
  24572. }
  24573. if (parsedTexture.mirrorPlane) {
  24574. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24575. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24576. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24577. return mirrorTexture;
  24578. }
  24579. else if (parsedTexture.isRenderTarget) {
  24580. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24581. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24582. return renderTargetTexture;
  24583. }
  24584. else {
  24585. var texture;
  24586. if (parsedTexture.base64String) {
  24587. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24588. }
  24589. else {
  24590. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24591. }
  24592. return texture;
  24593. }
  24594. }, parsedTexture, scene);
  24595. // Update Sampling Mode
  24596. if (parsedTexture.samplingMode) {
  24597. var sampling = parsedTexture.samplingMode;
  24598. if (texture._samplingMode !== sampling) {
  24599. texture.updateSamplingMode(sampling);
  24600. }
  24601. }
  24602. // Animations
  24603. if (parsedTexture.animations) {
  24604. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24605. var parsedAnimation = parsedTexture.animations[animationIndex];
  24606. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24607. }
  24608. }
  24609. return texture;
  24610. };
  24611. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24612. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24613. if (noMipmap === void 0) { noMipmap = false; }
  24614. if (invertY === void 0) { invertY = true; }
  24615. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24616. if (onLoad === void 0) { onLoad = null; }
  24617. if (onError === void 0) { onError = null; }
  24618. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24619. if (name.substr(0, 5) !== "data:") {
  24620. name = "data:" + name;
  24621. }
  24622. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24623. };
  24624. // Constants
  24625. Texture.NEAREST_SAMPLINGMODE = 1;
  24626. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24627. Texture.BILINEAR_SAMPLINGMODE = 2;
  24628. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24629. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24630. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24631. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24632. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24633. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24634. Texture.NEAREST_LINEAR = 7;
  24635. Texture.NEAREST_NEAREST = 8;
  24636. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24637. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24638. Texture.LINEAR_LINEAR = 11;
  24639. Texture.LINEAR_NEAREST = 12;
  24640. Texture.EXPLICIT_MODE = 0;
  24641. Texture.SPHERICAL_MODE = 1;
  24642. Texture.PLANAR_MODE = 2;
  24643. Texture.CUBIC_MODE = 3;
  24644. Texture.PROJECTION_MODE = 4;
  24645. Texture.SKYBOX_MODE = 5;
  24646. Texture.INVCUBIC_MODE = 6;
  24647. Texture.EQUIRECTANGULAR_MODE = 7;
  24648. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24649. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24650. Texture.CLAMP_ADDRESSMODE = 0;
  24651. Texture.WRAP_ADDRESSMODE = 1;
  24652. Texture.MIRROR_ADDRESSMODE = 2;
  24653. __decorate([
  24654. BABYLON.serialize()
  24655. ], Texture.prototype, "url", void 0);
  24656. __decorate([
  24657. BABYLON.serialize()
  24658. ], Texture.prototype, "uOffset", void 0);
  24659. __decorate([
  24660. BABYLON.serialize()
  24661. ], Texture.prototype, "vOffset", void 0);
  24662. __decorate([
  24663. BABYLON.serialize()
  24664. ], Texture.prototype, "uScale", void 0);
  24665. __decorate([
  24666. BABYLON.serialize()
  24667. ], Texture.prototype, "vScale", void 0);
  24668. __decorate([
  24669. BABYLON.serialize()
  24670. ], Texture.prototype, "uAng", void 0);
  24671. __decorate([
  24672. BABYLON.serialize()
  24673. ], Texture.prototype, "vAng", void 0);
  24674. __decorate([
  24675. BABYLON.serialize()
  24676. ], Texture.prototype, "wAng", void 0);
  24677. __decorate([
  24678. BABYLON.serialize()
  24679. ], Texture.prototype, "isBlocking", null);
  24680. return Texture;
  24681. }(BABYLON.BaseTexture));
  24682. BABYLON.Texture = Texture;
  24683. })(BABYLON || (BABYLON = {}));
  24684. //# sourceMappingURL=babylon.texture.js.map
  24685. var BABYLON;
  24686. (function (BABYLON) {
  24687. var _InstancesBatch = /** @class */ (function () {
  24688. function _InstancesBatch() {
  24689. this.mustReturn = false;
  24690. this.visibleInstances = new Array();
  24691. this.renderSelf = new Array();
  24692. }
  24693. return _InstancesBatch;
  24694. }());
  24695. BABYLON._InstancesBatch = _InstancesBatch;
  24696. var Mesh = /** @class */ (function (_super) {
  24697. __extends(Mesh, _super);
  24698. /**
  24699. * @constructor
  24700. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24701. * @param {Scene} scene The scene to add this mesh to.
  24702. * @param {Node} parent The parent of this mesh, if it has one
  24703. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24704. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24705. * When false, achieved by calling a clone(), also passing False.
  24706. * This will make creation of children, recursive.
  24707. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24708. */
  24709. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24710. if (scene === void 0) { scene = null; }
  24711. if (parent === void 0) { parent = null; }
  24712. if (source === void 0) { source = null; }
  24713. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24714. var _this = _super.call(this, name, scene) || this;
  24715. // Events
  24716. /**
  24717. * An event triggered before rendering the mesh
  24718. * @type {BABYLON.Observable}
  24719. */
  24720. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24721. /**
  24722. * An event triggered after rendering the mesh
  24723. * @type {BABYLON.Observable}
  24724. */
  24725. _this.onAfterRenderObservable = new BABYLON.Observable();
  24726. /**
  24727. * An event triggered before drawing the mesh
  24728. * @type {BABYLON.Observable}
  24729. */
  24730. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24731. // Members
  24732. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24733. _this.instances = new Array();
  24734. _this._LODLevels = new Array();
  24735. _this._visibleInstances = {};
  24736. _this._renderIdForInstances = new Array();
  24737. _this._batchCache = new _InstancesBatch();
  24738. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24739. // Use by builder only to know what orientation were the mesh build in.
  24740. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24741. _this.overrideMaterialSideOrientation = null;
  24742. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24743. // Will be used to save a source mesh reference, If any
  24744. _this._source = null;
  24745. scene = _this.getScene();
  24746. if (source) {
  24747. // Source mesh
  24748. _this._source = source;
  24749. // Geometry
  24750. if (source._geometry) {
  24751. source._geometry.applyToMesh(_this);
  24752. }
  24753. // Deep copy
  24754. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24755. // Metadata
  24756. if (source.metadata && source.metadata.clone) {
  24757. _this.metadata = source.metadata.clone();
  24758. }
  24759. else {
  24760. _this.metadata = source.metadata;
  24761. }
  24762. // Tags
  24763. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24764. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24765. }
  24766. // Parent
  24767. _this.parent = source.parent;
  24768. // Pivot
  24769. _this.setPivotMatrix(source.getPivotMatrix());
  24770. _this.id = name + "." + source.id;
  24771. // Material
  24772. _this.material = source.material;
  24773. var index;
  24774. if (!doNotCloneChildren) {
  24775. // Children
  24776. var directDescendants = source.getDescendants(true);
  24777. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24778. var child = directDescendants[index_1];
  24779. if (child.clone) {
  24780. child.clone(name + "." + child.name, _this);
  24781. }
  24782. }
  24783. }
  24784. // Physics clone
  24785. var physicsEngine = _this.getScene().getPhysicsEngine();
  24786. if (clonePhysicsImpostor && physicsEngine) {
  24787. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24788. if (impostor) {
  24789. _this.physicsImpostor = impostor.clone(_this);
  24790. }
  24791. }
  24792. // Particles
  24793. for (index = 0; index < scene.particleSystems.length; index++) {
  24794. var system = scene.particleSystems[index];
  24795. if (system.emitter === source) {
  24796. system.clone(system.name, _this);
  24797. }
  24798. }
  24799. _this.computeWorldMatrix(true);
  24800. }
  24801. // Parent
  24802. if (parent !== null) {
  24803. _this.parent = parent;
  24804. }
  24805. return _this;
  24806. }
  24807. Object.defineProperty(Mesh, "FRONTSIDE", {
  24808. /**
  24809. * Mesh side orientation : usually the external or front surface
  24810. */
  24811. get: function () {
  24812. return Mesh._FRONTSIDE;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. Object.defineProperty(Mesh, "BACKSIDE", {
  24818. /**
  24819. * Mesh side orientation : usually the internal or back surface
  24820. */
  24821. get: function () {
  24822. return Mesh._BACKSIDE;
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24828. /**
  24829. * Mesh side orientation : both internal and external or front and back surfaces
  24830. */
  24831. get: function () {
  24832. return Mesh._DOUBLESIDE;
  24833. },
  24834. enumerable: true,
  24835. configurable: true
  24836. });
  24837. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24838. /**
  24839. * Mesh side orientation : by default, `FRONTSIDE`
  24840. */
  24841. get: function () {
  24842. return Mesh._DEFAULTSIDE;
  24843. },
  24844. enumerable: true,
  24845. configurable: true
  24846. });
  24847. Object.defineProperty(Mesh, "NO_CAP", {
  24848. /**
  24849. * Mesh cap setting : no cap
  24850. */
  24851. get: function () {
  24852. return Mesh._NO_CAP;
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. Object.defineProperty(Mesh, "CAP_START", {
  24858. /**
  24859. * Mesh cap setting : one cap at the beginning of the mesh
  24860. */
  24861. get: function () {
  24862. return Mesh._CAP_START;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. Object.defineProperty(Mesh, "CAP_END", {
  24868. /**
  24869. * Mesh cap setting : one cap at the end of the mesh
  24870. */
  24871. get: function () {
  24872. return Mesh._CAP_END;
  24873. },
  24874. enumerable: true,
  24875. configurable: true
  24876. });
  24877. Object.defineProperty(Mesh, "CAP_ALL", {
  24878. /**
  24879. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24880. */
  24881. get: function () {
  24882. return Mesh._CAP_ALL;
  24883. },
  24884. enumerable: true,
  24885. configurable: true
  24886. });
  24887. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24888. set: function (callback) {
  24889. if (this._onBeforeDrawObserver) {
  24890. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24891. }
  24892. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24898. get: function () {
  24899. return this._morphTargetManager;
  24900. },
  24901. set: function (value) {
  24902. if (this._morphTargetManager === value) {
  24903. return;
  24904. }
  24905. this._morphTargetManager = value;
  24906. this._syncGeometryWithMorphTargetManager();
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(Mesh.prototype, "source", {
  24912. get: function () {
  24913. return this._source;
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24919. get: function () {
  24920. return this._unIndexed;
  24921. },
  24922. set: function (value) {
  24923. if (this._unIndexed !== value) {
  24924. this._unIndexed = value;
  24925. this._markSubMeshesAsAttributesDirty();
  24926. }
  24927. },
  24928. enumerable: true,
  24929. configurable: true
  24930. });
  24931. // Methods
  24932. /**
  24933. * Returns the string "Mesh".
  24934. */
  24935. Mesh.prototype.getClassName = function () {
  24936. return "Mesh";
  24937. };
  24938. /**
  24939. * Returns a string.
  24940. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24941. */
  24942. Mesh.prototype.toString = function (fullDetails) {
  24943. var ret = _super.prototype.toString.call(this, fullDetails);
  24944. ret += ", n vertices: " + this.getTotalVertices();
  24945. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24946. if (this.animations) {
  24947. for (var i = 0; i < this.animations.length; i++) {
  24948. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24949. }
  24950. }
  24951. if (fullDetails) {
  24952. if (this._geometry) {
  24953. var ib = this.getIndices();
  24954. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24955. if (vb && ib) {
  24956. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24957. }
  24958. }
  24959. else {
  24960. ret += ", flat shading: UNKNOWN";
  24961. }
  24962. }
  24963. return ret;
  24964. };
  24965. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24966. /**
  24967. * True if the mesh has some Levels Of Details (LOD).
  24968. * Returns a boolean.
  24969. */
  24970. get: function () {
  24971. return this._LODLevels.length > 0;
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. Mesh.prototype._sortLODLevels = function () {
  24977. this._LODLevels.sort(function (a, b) {
  24978. if (a.distance < b.distance) {
  24979. return 1;
  24980. }
  24981. if (a.distance > b.distance) {
  24982. return -1;
  24983. }
  24984. return 0;
  24985. });
  24986. };
  24987. /**
  24988. * Add a mesh as LOD level triggered at the given distance.
  24989. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24990. * @param {number} distance The distance from the center of the object to show this level
  24991. * @param {Mesh} mesh The mesh to be added as LOD level
  24992. * @return {Mesh} This mesh (for chaining)
  24993. */
  24994. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24995. if (mesh && mesh._masterMesh) {
  24996. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24997. return this;
  24998. }
  24999. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25000. this._LODLevels.push(level);
  25001. if (mesh) {
  25002. mesh._masterMesh = this;
  25003. }
  25004. this._sortLODLevels();
  25005. return this;
  25006. };
  25007. /**
  25008. * Returns the LOD level mesh at the passed distance or null if not found.
  25009. * It is related to the method `addLODLevel(distance, mesh)`.
  25010. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25011. * Returns an object Mesh or `null`.
  25012. */
  25013. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25014. for (var index = 0; index < this._LODLevels.length; index++) {
  25015. var level = this._LODLevels[index];
  25016. if (level.distance === distance) {
  25017. return level.mesh;
  25018. }
  25019. }
  25020. return null;
  25021. };
  25022. /**
  25023. * Remove a mesh from the LOD array
  25024. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25025. * @param {Mesh} mesh The mesh to be removed.
  25026. * @return {Mesh} This mesh (for chaining)
  25027. */
  25028. Mesh.prototype.removeLODLevel = function (mesh) {
  25029. for (var index = 0; index < this._LODLevels.length; index++) {
  25030. if (this._LODLevels[index].mesh === mesh) {
  25031. this._LODLevels.splice(index, 1);
  25032. if (mesh) {
  25033. mesh._masterMesh = null;
  25034. }
  25035. }
  25036. }
  25037. this._sortLODLevels();
  25038. return this;
  25039. };
  25040. /**
  25041. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25042. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25043. */
  25044. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25045. if (!this._LODLevels || this._LODLevels.length === 0) {
  25046. return this;
  25047. }
  25048. var bSphere;
  25049. if (boundingSphere) {
  25050. bSphere = boundingSphere;
  25051. }
  25052. else {
  25053. var boundingInfo = this.getBoundingInfo();
  25054. bSphere = boundingInfo.boundingSphere;
  25055. }
  25056. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25057. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25058. if (this.onLODLevelSelection) {
  25059. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25060. }
  25061. return this;
  25062. }
  25063. for (var index = 0; index < this._LODLevels.length; index++) {
  25064. var level = this._LODLevels[index];
  25065. if (level.distance < distanceToCamera) {
  25066. if (level.mesh) {
  25067. level.mesh._preActivate();
  25068. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25069. }
  25070. if (this.onLODLevelSelection) {
  25071. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25072. }
  25073. return level.mesh;
  25074. }
  25075. }
  25076. if (this.onLODLevelSelection) {
  25077. this.onLODLevelSelection(distanceToCamera, this, this);
  25078. }
  25079. return this;
  25080. };
  25081. Object.defineProperty(Mesh.prototype, "geometry", {
  25082. /**
  25083. * Returns the mesh internal Geometry object.
  25084. */
  25085. get: function () {
  25086. return this._geometry;
  25087. },
  25088. enumerable: true,
  25089. configurable: true
  25090. });
  25091. /**
  25092. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25093. */
  25094. Mesh.prototype.getTotalVertices = function () {
  25095. if (this._geometry === null || this._geometry === undefined) {
  25096. return 0;
  25097. }
  25098. return this._geometry.getTotalVertices();
  25099. };
  25100. /**
  25101. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25102. * 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.
  25103. * You can force the copy with forceCopy === true
  25104. * Returns null if the mesh has no geometry or no vertex buffer.
  25105. * Possible `kind` values :
  25106. * - BABYLON.VertexBuffer.PositionKind
  25107. * - BABYLON.VertexBuffer.UVKind
  25108. * - BABYLON.VertexBuffer.UV2Kind
  25109. * - BABYLON.VertexBuffer.UV3Kind
  25110. * - BABYLON.VertexBuffer.UV4Kind
  25111. * - BABYLON.VertexBuffer.UV5Kind
  25112. * - BABYLON.VertexBuffer.UV6Kind
  25113. * - BABYLON.VertexBuffer.ColorKind
  25114. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25115. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25116. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25117. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25118. */
  25119. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25120. if (!this._geometry) {
  25121. return null;
  25122. }
  25123. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25124. };
  25125. /**
  25126. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25127. * Returns `null` if the mesh has no geometry.
  25128. * Possible `kind` values :
  25129. * - BABYLON.VertexBuffer.PositionKind
  25130. * - BABYLON.VertexBuffer.UVKind
  25131. * - BABYLON.VertexBuffer.UV2Kind
  25132. * - BABYLON.VertexBuffer.UV3Kind
  25133. * - BABYLON.VertexBuffer.UV4Kind
  25134. * - BABYLON.VertexBuffer.UV5Kind
  25135. * - BABYLON.VertexBuffer.UV6Kind
  25136. * - BABYLON.VertexBuffer.ColorKind
  25137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25141. */
  25142. Mesh.prototype.getVertexBuffer = function (kind) {
  25143. if (!this._geometry) {
  25144. return null;
  25145. }
  25146. return this._geometry.getVertexBuffer(kind);
  25147. };
  25148. /**
  25149. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25150. * Possible `kind` values :
  25151. * - BABYLON.VertexBuffer.PositionKind
  25152. * - BABYLON.VertexBuffer.UVKind
  25153. * - BABYLON.VertexBuffer.UV2Kind
  25154. * - BABYLON.VertexBuffer.UV3Kind
  25155. * - BABYLON.VertexBuffer.UV4Kind
  25156. * - BABYLON.VertexBuffer.UV5Kind
  25157. * - BABYLON.VertexBuffer.UV6Kind
  25158. * - BABYLON.VertexBuffer.ColorKind
  25159. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25160. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25161. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25162. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25163. */
  25164. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25165. if (!this._geometry) {
  25166. if (this._delayInfo) {
  25167. return this._delayInfo.indexOf(kind) !== -1;
  25168. }
  25169. return false;
  25170. }
  25171. return this._geometry.isVerticesDataPresent(kind);
  25172. };
  25173. /**
  25174. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25175. * Possible `kind` values :
  25176. * - BABYLON.VertexBuffer.PositionKind
  25177. * - BABYLON.VertexBuffer.UVKind
  25178. * - BABYLON.VertexBuffer.UV2Kind
  25179. * - BABYLON.VertexBuffer.UV3Kind
  25180. * - BABYLON.VertexBuffer.UV4Kind
  25181. * - BABYLON.VertexBuffer.UV5Kind
  25182. * - BABYLON.VertexBuffer.UV6Kind
  25183. * - BABYLON.VertexBuffer.ColorKind
  25184. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25185. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25186. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25187. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25188. */
  25189. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25190. if (!this._geometry) {
  25191. if (this._delayInfo) {
  25192. return this._delayInfo.indexOf(kind) !== -1;
  25193. }
  25194. return false;
  25195. }
  25196. return this._geometry.isVertexBufferUpdatable(kind);
  25197. };
  25198. /**
  25199. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25200. * Possible `kind` values :
  25201. * - BABYLON.VertexBuffer.PositionKind
  25202. * - BABYLON.VertexBuffer.UVKind
  25203. * - BABYLON.VertexBuffer.UV2Kind
  25204. * - BABYLON.VertexBuffer.UV3Kind
  25205. * - BABYLON.VertexBuffer.UV4Kind
  25206. * - BABYLON.VertexBuffer.UV5Kind
  25207. * - BABYLON.VertexBuffer.UV6Kind
  25208. * - BABYLON.VertexBuffer.ColorKind
  25209. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25210. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25211. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25212. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25213. */
  25214. Mesh.prototype.getVerticesDataKinds = function () {
  25215. if (!this._geometry) {
  25216. var result = new Array();
  25217. if (this._delayInfo) {
  25218. this._delayInfo.forEach(function (kind, index, array) {
  25219. result.push(kind);
  25220. });
  25221. }
  25222. return result;
  25223. }
  25224. return this._geometry.getVerticesDataKinds();
  25225. };
  25226. /**
  25227. * Returns a positive integer : the total number of indices in this mesh geometry.
  25228. * Returns zero if the mesh has no geometry.
  25229. */
  25230. Mesh.prototype.getTotalIndices = function () {
  25231. if (!this._geometry) {
  25232. return 0;
  25233. }
  25234. return this._geometry.getTotalIndices();
  25235. };
  25236. /**
  25237. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25238. * 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.
  25239. * Returns an empty array if the mesh has no geometry.
  25240. */
  25241. Mesh.prototype.getIndices = function (copyWhenShared) {
  25242. if (!this._geometry) {
  25243. return [];
  25244. }
  25245. return this._geometry.getIndices(copyWhenShared);
  25246. };
  25247. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25248. get: function () {
  25249. return this._masterMesh !== null && this._masterMesh !== undefined;
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. /**
  25255. * Determine if the current mesh is ready to be rendered
  25256. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25257. * @returns true if all associated assets are ready (material, textures, shaders)
  25258. */
  25259. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25260. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25261. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25262. return false;
  25263. }
  25264. if (!_super.prototype.isReady.call(this)) {
  25265. return false;
  25266. }
  25267. if (!this.subMeshes || this.subMeshes.length === 0) {
  25268. return true;
  25269. }
  25270. var engine = this.getEngine();
  25271. var scene = this.getScene();
  25272. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25273. this.computeWorldMatrix();
  25274. var mat = this.material || scene.defaultMaterial;
  25275. if (mat) {
  25276. var currentAlphaTestingState = engine.getAlphaTesting();
  25277. if (mat.storeEffectOnSubMeshes) {
  25278. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25279. var subMesh = _a[_i];
  25280. var effectiveMaterial = subMesh.getMaterial();
  25281. if (effectiveMaterial) {
  25282. engine.setAlphaTesting(effectiveMaterial.needAlphaTesting() && !effectiveMaterial.needAlphaBlendingForMesh(this));
  25283. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25284. engine.setAlphaTesting(currentAlphaTestingState);
  25285. return false;
  25286. }
  25287. }
  25288. }
  25289. }
  25290. else {
  25291. engine.setAlphaTesting(mat.needAlphaTesting() && !mat.needAlphaBlendingForMesh(this));
  25292. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25293. engine.setAlphaTesting(currentAlphaTestingState);
  25294. return false;
  25295. }
  25296. }
  25297. engine.setAlphaTesting(currentAlphaTestingState);
  25298. }
  25299. // Shadows
  25300. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25301. var light = _c[_b];
  25302. var generator = light.getShadowGenerator();
  25303. if (generator) {
  25304. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25305. var subMesh = _e[_d];
  25306. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25307. return false;
  25308. }
  25309. }
  25310. }
  25311. }
  25312. // LOD
  25313. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25314. var lod = _g[_f];
  25315. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25316. return false;
  25317. }
  25318. }
  25319. return true;
  25320. };
  25321. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25322. /**
  25323. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25324. * This property is pertinent only for updatable parametric shapes.
  25325. */
  25326. get: function () {
  25327. return this._areNormalsFrozen;
  25328. },
  25329. enumerable: true,
  25330. configurable: true
  25331. });
  25332. /**
  25333. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25334. * It has no effect at all on other shapes.
  25335. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25336. * Returns the Mesh.
  25337. */
  25338. Mesh.prototype.freezeNormals = function () {
  25339. this._areNormalsFrozen = true;
  25340. return this;
  25341. };
  25342. /**
  25343. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25344. * It has no effect at all on other shapes.
  25345. * It reactivates the mesh normals computation if it was previously frozen.
  25346. * Returns the Mesh.
  25347. */
  25348. Mesh.prototype.unfreezeNormals = function () {
  25349. this._areNormalsFrozen = false;
  25350. return this;
  25351. };
  25352. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25353. /**
  25354. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25355. */
  25356. set: function (count) {
  25357. this._overridenInstanceCount = count;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. // Methods
  25363. Mesh.prototype._preActivate = function () {
  25364. var sceneRenderId = this.getScene().getRenderId();
  25365. if (this._preActivateId === sceneRenderId) {
  25366. return this;
  25367. }
  25368. this._preActivateId = sceneRenderId;
  25369. this._visibleInstances = null;
  25370. return this;
  25371. };
  25372. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25373. if (this._visibleInstances) {
  25374. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25375. }
  25376. return this;
  25377. };
  25378. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25379. if (!this._visibleInstances) {
  25380. this._visibleInstances = {};
  25381. this._visibleInstances.defaultRenderId = renderId;
  25382. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25383. }
  25384. if (!this._visibleInstances[renderId]) {
  25385. this._visibleInstances[renderId] = new Array();
  25386. }
  25387. this._visibleInstances[renderId].push(instance);
  25388. return this;
  25389. };
  25390. /**
  25391. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25392. * This means the mesh underlying bounding box and sphere are recomputed.
  25393. * Returns the Mesh.
  25394. */
  25395. Mesh.prototype.refreshBoundingInfo = function () {
  25396. return this._refreshBoundingInfo(false);
  25397. };
  25398. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25399. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25400. return this;
  25401. }
  25402. var data = this._getPositionData(applySkeleton);
  25403. if (data) {
  25404. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25405. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25406. }
  25407. if (this.subMeshes) {
  25408. for (var index = 0; index < this.subMeshes.length; index++) {
  25409. this.subMeshes[index].refreshBoundingInfo();
  25410. }
  25411. }
  25412. this._updateBoundingInfo();
  25413. return this;
  25414. };
  25415. Mesh.prototype._getPositionData = function (applySkeleton) {
  25416. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25417. if (data && applySkeleton && this.skeleton) {
  25418. data = data.slice();
  25419. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25420. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25421. if (matricesWeightsData && matricesIndicesData) {
  25422. var needExtras = this.numBoneInfluencers > 4;
  25423. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25424. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25425. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25426. var tempVector = BABYLON.Tmp.Vector3[0];
  25427. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25428. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25429. var matWeightIdx = 0;
  25430. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25431. finalMatrix.reset();
  25432. var inf;
  25433. var weight;
  25434. for (inf = 0; inf < 4; inf++) {
  25435. weight = matricesWeightsData[matWeightIdx + inf];
  25436. if (weight <= 0)
  25437. break;
  25438. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25439. finalMatrix.addToSelf(tempMatrix);
  25440. }
  25441. if (needExtras) {
  25442. for (inf = 0; inf < 4; inf++) {
  25443. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25444. if (weight <= 0)
  25445. break;
  25446. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25447. finalMatrix.addToSelf(tempMatrix);
  25448. }
  25449. }
  25450. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25451. tempVector.toArray(data, index);
  25452. }
  25453. }
  25454. }
  25455. return data;
  25456. };
  25457. Mesh.prototype._createGlobalSubMesh = function (force) {
  25458. var totalVertices = this.getTotalVertices();
  25459. if (!totalVertices || !this.getIndices()) {
  25460. return null;
  25461. }
  25462. // Check if we need to recreate the submeshes
  25463. if (this.subMeshes && this.subMeshes.length > 0) {
  25464. var ib = this.getIndices();
  25465. if (!ib) {
  25466. return null;
  25467. }
  25468. var totalIndices = ib.length;
  25469. var needToRecreate = false;
  25470. if (force) {
  25471. needToRecreate = true;
  25472. }
  25473. else {
  25474. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25475. var submesh = _a[_i];
  25476. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25477. needToRecreate = true;
  25478. break;
  25479. }
  25480. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25481. needToRecreate = true;
  25482. break;
  25483. }
  25484. }
  25485. }
  25486. if (!needToRecreate) {
  25487. return this.subMeshes[0];
  25488. }
  25489. }
  25490. this.releaseSubMeshes();
  25491. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25492. };
  25493. Mesh.prototype.subdivide = function (count) {
  25494. if (count < 1) {
  25495. return;
  25496. }
  25497. var totalIndices = this.getTotalIndices();
  25498. var subdivisionSize = (totalIndices / count) | 0;
  25499. var offset = 0;
  25500. // Ensure that subdivisionSize is a multiple of 3
  25501. while (subdivisionSize % 3 !== 0) {
  25502. subdivisionSize++;
  25503. }
  25504. this.releaseSubMeshes();
  25505. for (var index = 0; index < count; index++) {
  25506. if (offset >= totalIndices) {
  25507. break;
  25508. }
  25509. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25510. offset += subdivisionSize;
  25511. }
  25512. this.synchronizeInstances();
  25513. };
  25514. /**
  25515. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25516. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25517. * The `data` are either a numeric array either a Float32Array.
  25518. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25519. * 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).
  25520. * Note that a new underlying VertexBuffer object is created each call.
  25521. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25522. *
  25523. * Possible `kind` values :
  25524. * - BABYLON.VertexBuffer.PositionKind
  25525. * - BABYLON.VertexBuffer.UVKind
  25526. * - BABYLON.VertexBuffer.UV2Kind
  25527. * - BABYLON.VertexBuffer.UV3Kind
  25528. * - BABYLON.VertexBuffer.UV4Kind
  25529. * - BABYLON.VertexBuffer.UV5Kind
  25530. * - BABYLON.VertexBuffer.UV6Kind
  25531. * - BABYLON.VertexBuffer.ColorKind
  25532. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25533. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25534. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25535. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25536. *
  25537. * Returns the Mesh.
  25538. */
  25539. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25540. if (updatable === void 0) { updatable = false; }
  25541. if (!this._geometry) {
  25542. var vertexData = new BABYLON.VertexData();
  25543. vertexData.set(data, kind);
  25544. var scene = this.getScene();
  25545. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25546. }
  25547. else {
  25548. this._geometry.setVerticesData(kind, data, updatable, stride);
  25549. }
  25550. return this;
  25551. };
  25552. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25553. if (updatable === void 0) { updatable = true; }
  25554. var vb = this.getVertexBuffer(kind);
  25555. if (!vb || vb.isUpdatable() === updatable) {
  25556. return;
  25557. }
  25558. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25559. };
  25560. /**
  25561. * Sets the mesh VertexBuffer.
  25562. * Returns the Mesh.
  25563. */
  25564. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25565. if (!this._geometry) {
  25566. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25567. }
  25568. this._geometry.setVerticesBuffer(buffer);
  25569. return this;
  25570. };
  25571. /**
  25572. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25573. * If the mesh has no geometry, it is simply returned as it is.
  25574. * The `data` are either a numeric array either a Float32Array.
  25575. * No new underlying VertexBuffer object is created.
  25576. * 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.
  25577. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25578. *
  25579. * Possible `kind` values :
  25580. * - BABYLON.VertexBuffer.PositionKind
  25581. * - BABYLON.VertexBuffer.UVKind
  25582. * - BABYLON.VertexBuffer.UV2Kind
  25583. * - BABYLON.VertexBuffer.UV3Kind
  25584. * - BABYLON.VertexBuffer.UV4Kind
  25585. * - BABYLON.VertexBuffer.UV5Kind
  25586. * - BABYLON.VertexBuffer.UV6Kind
  25587. * - BABYLON.VertexBuffer.ColorKind
  25588. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25589. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25590. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25591. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25592. *
  25593. * Returns the Mesh.
  25594. */
  25595. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25596. if (!this._geometry) {
  25597. return this;
  25598. }
  25599. if (!makeItUnique) {
  25600. this._geometry.updateVerticesData(kind, data, updateExtends);
  25601. }
  25602. else {
  25603. this.makeGeometryUnique();
  25604. this.updateVerticesData(kind, data, updateExtends, false);
  25605. }
  25606. return this;
  25607. };
  25608. /**
  25609. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25610. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25611. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25612. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25613. * Returns the Mesh.
  25614. */
  25615. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25616. if (computeNormals === void 0) { computeNormals = true; }
  25617. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25618. if (!positions) {
  25619. return this;
  25620. }
  25621. positionFunction(positions);
  25622. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25623. if (computeNormals) {
  25624. var indices = this.getIndices();
  25625. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25626. if (!normals) {
  25627. return this;
  25628. }
  25629. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25630. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25631. }
  25632. return this;
  25633. };
  25634. /**
  25635. * Creates a un-shared specific occurence of the geometry for the mesh.
  25636. * Returns the Mesh.
  25637. */
  25638. Mesh.prototype.makeGeometryUnique = function () {
  25639. if (!this._geometry) {
  25640. return this;
  25641. }
  25642. var oldGeometry = this._geometry;
  25643. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25644. oldGeometry.releaseForMesh(this, true);
  25645. geometry.applyToMesh(this);
  25646. return this;
  25647. };
  25648. /**
  25649. * Sets the mesh indices.
  25650. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25651. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25652. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25653. * This method creates a new index buffer each call.
  25654. * Returns the Mesh.
  25655. */
  25656. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25657. if (totalVertices === void 0) { totalVertices = null; }
  25658. if (updatable === void 0) { updatable = false; }
  25659. if (!this._geometry) {
  25660. var vertexData = new BABYLON.VertexData();
  25661. vertexData.indices = indices;
  25662. var scene = this.getScene();
  25663. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25664. }
  25665. else {
  25666. this._geometry.setIndices(indices, totalVertices, updatable);
  25667. }
  25668. return this;
  25669. };
  25670. /**
  25671. * Update the current index buffer
  25672. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25673. * Returns the Mesh.
  25674. */
  25675. Mesh.prototype.updateIndices = function (indices, offset) {
  25676. if (!this._geometry) {
  25677. return this;
  25678. }
  25679. this._geometry.updateIndices(indices, offset);
  25680. return this;
  25681. };
  25682. /**
  25683. * Invert the geometry to move from a right handed system to a left handed one.
  25684. * Returns the Mesh.
  25685. */
  25686. Mesh.prototype.toLeftHanded = function () {
  25687. if (!this._geometry) {
  25688. return this;
  25689. }
  25690. this._geometry.toLeftHanded();
  25691. return this;
  25692. };
  25693. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25694. if (!this._geometry) {
  25695. return this;
  25696. }
  25697. var engine = this.getScene().getEngine();
  25698. // Wireframe
  25699. var indexToBind;
  25700. if (this._unIndexed) {
  25701. indexToBind = null;
  25702. }
  25703. else {
  25704. switch (fillMode) {
  25705. case BABYLON.Material.PointFillMode:
  25706. indexToBind = null;
  25707. break;
  25708. case BABYLON.Material.WireFrameFillMode:
  25709. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25710. break;
  25711. default:
  25712. case BABYLON.Material.TriangleFillMode:
  25713. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25714. break;
  25715. }
  25716. }
  25717. // VBOs
  25718. this._geometry._bind(effect, indexToBind);
  25719. return this;
  25720. };
  25721. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25722. if (alternate === void 0) { alternate = false; }
  25723. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25724. return this;
  25725. }
  25726. this.onBeforeDrawObservable.notifyObservers(this);
  25727. var scene = this.getScene();
  25728. var engine = scene.getEngine();
  25729. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25730. // or triangles as points
  25731. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25732. }
  25733. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25734. // Triangles as wireframe
  25735. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25736. }
  25737. else {
  25738. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25739. }
  25740. if (scene._isAlternateRenderingEnabled && !alternate) {
  25741. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25742. if (!effect || !scene.activeCamera) {
  25743. return this;
  25744. }
  25745. scene._switchToAlternateCameraConfiguration(true);
  25746. this._effectiveMaterial.bindView(effect);
  25747. this._effectiveMaterial.bindViewProjection(effect);
  25748. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25749. this._draw(subMesh, fillMode, instancesCount, true);
  25750. engine.setViewport(scene.activeCamera.viewport);
  25751. scene._switchToAlternateCameraConfiguration(false);
  25752. this._effectiveMaterial.bindView(effect);
  25753. this._effectiveMaterial.bindViewProjection(effect);
  25754. }
  25755. return this;
  25756. };
  25757. /**
  25758. * Registers for this mesh a javascript function called just before the rendering process.
  25759. * This function is passed the current mesh.
  25760. * Return the Mesh.
  25761. */
  25762. Mesh.prototype.registerBeforeRender = function (func) {
  25763. this.onBeforeRenderObservable.add(func);
  25764. return this;
  25765. };
  25766. /**
  25767. * Disposes a previously registered javascript function called before the rendering.
  25768. * This function is passed the current mesh.
  25769. * Returns the Mesh.
  25770. */
  25771. Mesh.prototype.unregisterBeforeRender = function (func) {
  25772. this.onBeforeRenderObservable.removeCallback(func);
  25773. return this;
  25774. };
  25775. /**
  25776. * Registers for this mesh a javascript function called just after the rendering is complete.
  25777. * This function is passed the current mesh.
  25778. * Returns the Mesh.
  25779. */
  25780. Mesh.prototype.registerAfterRender = function (func) {
  25781. this.onAfterRenderObservable.add(func);
  25782. return this;
  25783. };
  25784. /**
  25785. * Disposes a previously registered javascript function called after the rendering.
  25786. * This function is passed the current mesh.
  25787. * Return the Mesh.
  25788. */
  25789. Mesh.prototype.unregisterAfterRender = function (func) {
  25790. this.onAfterRenderObservable.removeCallback(func);
  25791. return this;
  25792. };
  25793. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25794. var scene = this.getScene();
  25795. this._batchCache.mustReturn = false;
  25796. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25797. this._batchCache.visibleInstances[subMeshId] = null;
  25798. if (this._visibleInstances) {
  25799. var currentRenderId = scene.getRenderId();
  25800. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25801. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25802. var selfRenderId = this._renderId;
  25803. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25804. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25805. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25806. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25807. }
  25808. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25809. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25810. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25811. this._batchCache.mustReturn = true;
  25812. return this._batchCache;
  25813. }
  25814. if (currentRenderId !== selfRenderId) {
  25815. this._batchCache.renderSelf[subMeshId] = false;
  25816. }
  25817. }
  25818. this._renderIdForInstances[subMeshId] = currentRenderId;
  25819. }
  25820. return this._batchCache;
  25821. };
  25822. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25823. var visibleInstances = batch.visibleInstances[subMesh._id];
  25824. if (!visibleInstances) {
  25825. return this;
  25826. }
  25827. var matricesCount = visibleInstances.length + 1;
  25828. var bufferSize = matricesCount * 16 * 4;
  25829. var currentInstancesBufferSize = this._instancesBufferSize;
  25830. var instancesBuffer = this._instancesBuffer;
  25831. while (this._instancesBufferSize < bufferSize) {
  25832. this._instancesBufferSize *= 2;
  25833. }
  25834. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25835. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25836. }
  25837. var offset = 0;
  25838. var instancesCount = 0;
  25839. var world = this.getWorldMatrix();
  25840. if (batch.renderSelf[subMesh._id]) {
  25841. world.copyToArray(this._instancesData, offset);
  25842. offset += 16;
  25843. instancesCount++;
  25844. }
  25845. if (visibleInstances) {
  25846. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25847. var instance = visibleInstances[instanceIndex];
  25848. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25849. offset += 16;
  25850. instancesCount++;
  25851. }
  25852. }
  25853. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25854. if (instancesBuffer) {
  25855. instancesBuffer.dispose();
  25856. }
  25857. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25858. this._instancesBuffer = instancesBuffer;
  25859. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25860. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25861. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25862. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25863. }
  25864. else {
  25865. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25866. }
  25867. this._bind(subMesh, effect, fillMode);
  25868. this._draw(subMesh, fillMode, instancesCount);
  25869. engine.unbindInstanceAttributes();
  25870. return this;
  25871. };
  25872. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25873. var scene = this.getScene();
  25874. var engine = scene.getEngine();
  25875. if (hardwareInstancedRendering) {
  25876. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25877. }
  25878. else {
  25879. if (batch.renderSelf[subMesh._id]) {
  25880. // Draw
  25881. if (onBeforeDraw) {
  25882. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25883. }
  25884. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25885. }
  25886. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25887. if (visibleInstancesForSubMesh) {
  25888. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25889. var instance = visibleInstancesForSubMesh[instanceIndex];
  25890. // World
  25891. var world = instance.getWorldMatrix();
  25892. if (onBeforeDraw) {
  25893. onBeforeDraw(true, world, effectiveMaterial);
  25894. }
  25895. // Draw
  25896. this._draw(subMesh, fillMode);
  25897. }
  25898. }
  25899. }
  25900. return this;
  25901. };
  25902. /**
  25903. * Triggers the draw call for the mesh.
  25904. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25905. * Returns the Mesh.
  25906. */
  25907. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25908. this.checkOcclusionQuery();
  25909. if (this._isOccluded) {
  25910. return this;
  25911. }
  25912. var scene = this.getScene();
  25913. // Managing instances
  25914. var batch = this._getInstancesRenderList(subMesh._id);
  25915. if (batch.mustReturn) {
  25916. return this;
  25917. }
  25918. // Checking geometry state
  25919. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25920. return this;
  25921. }
  25922. this.onBeforeRenderObservable.notifyObservers(this);
  25923. var engine = scene.getEngine();
  25924. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25925. // Material
  25926. var material = subMesh.getMaterial();
  25927. if (!material) {
  25928. return this;
  25929. }
  25930. this._effectiveMaterial = material;
  25931. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25932. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25933. return this;
  25934. }
  25935. }
  25936. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25937. return this;
  25938. }
  25939. // Alpha mode
  25940. if (enableAlphaMode) {
  25941. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25942. }
  25943. // Outline - step 1
  25944. var savedDepthWrite = engine.getDepthWrite();
  25945. if (this.renderOutline) {
  25946. engine.setDepthWrite(false);
  25947. scene.getOutlineRenderer().render(subMesh, batch);
  25948. engine.setDepthWrite(savedDepthWrite);
  25949. }
  25950. var effect;
  25951. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25952. effect = subMesh.effect;
  25953. }
  25954. else {
  25955. effect = this._effectiveMaterial.getEffect();
  25956. }
  25957. if (!effect) {
  25958. return this;
  25959. }
  25960. var sideOrientation = this.overrideMaterialSideOrientation;
  25961. if (sideOrientation == null) {
  25962. sideOrientation = this._effectiveMaterial.sideOrientation;
  25963. if (this._getWorldMatrixDeterminant() < 0) {
  25964. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25965. }
  25966. }
  25967. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25968. if (this._effectiveMaterial.forceDepthWrite) {
  25969. engine.setDepthWrite(true);
  25970. }
  25971. // Bind
  25972. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25973. if (!hardwareInstancedRendering) {
  25974. this._bind(subMesh, effect, fillMode);
  25975. }
  25976. var world = this.getWorldMatrix();
  25977. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25978. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25979. }
  25980. else {
  25981. this._effectiveMaterial.bind(world, this);
  25982. }
  25983. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25984. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25985. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25986. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25987. }
  25988. // Draw
  25989. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25990. // Unbind
  25991. this._effectiveMaterial.unbind();
  25992. // Outline - step 2
  25993. if (this.renderOutline && savedDepthWrite) {
  25994. engine.setDepthWrite(true);
  25995. engine.setColorWrite(false);
  25996. scene.getOutlineRenderer().render(subMesh, batch);
  25997. engine.setColorWrite(true);
  25998. }
  25999. // Overlay
  26000. if (this.renderOverlay) {
  26001. var currentMode = engine.getAlphaMode();
  26002. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26003. scene.getOutlineRenderer().render(subMesh, batch, true);
  26004. engine.setAlphaMode(currentMode);
  26005. }
  26006. this.onAfterRenderObservable.notifyObservers(this);
  26007. return this;
  26008. };
  26009. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26010. if (isInstance && effectiveMaterial) {
  26011. effectiveMaterial.bindOnlyWorldMatrix(world);
  26012. }
  26013. };
  26014. /**
  26015. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26016. */
  26017. Mesh.prototype.getEmittedParticleSystems = function () {
  26018. var results = new Array();
  26019. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26020. var particleSystem = this.getScene().particleSystems[index];
  26021. if (particleSystem.emitter === this) {
  26022. results.push(particleSystem);
  26023. }
  26024. }
  26025. return results;
  26026. };
  26027. /**
  26028. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26029. */
  26030. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26031. var results = new Array();
  26032. var descendants = this.getDescendants();
  26033. descendants.push(this);
  26034. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26035. var particleSystem = this.getScene().particleSystems[index];
  26036. var emitter = particleSystem.emitter;
  26037. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26038. results.push(particleSystem);
  26039. }
  26040. }
  26041. return results;
  26042. };
  26043. Mesh.prototype._checkDelayState = function () {
  26044. var scene = this.getScene();
  26045. if (this._geometry) {
  26046. this._geometry.load(scene);
  26047. }
  26048. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26050. this._queueLoad(scene);
  26051. }
  26052. return this;
  26053. };
  26054. Mesh.prototype._queueLoad = function (scene) {
  26055. var _this = this;
  26056. scene._addPendingData(this);
  26057. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26058. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26059. if (data instanceof ArrayBuffer) {
  26060. _this._delayLoadingFunction(data, _this);
  26061. }
  26062. else {
  26063. _this._delayLoadingFunction(JSON.parse(data), _this);
  26064. }
  26065. _this.instances.forEach(function (instance) {
  26066. instance._syncSubMeshes();
  26067. });
  26068. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26069. scene._removePendingData(_this);
  26070. }, function () { }, scene.database, getBinaryData);
  26071. return this;
  26072. };
  26073. /**
  26074. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26075. */
  26076. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26077. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26078. return false;
  26079. }
  26080. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26081. return false;
  26082. }
  26083. this._checkDelayState();
  26084. return true;
  26085. };
  26086. /**
  26087. * Sets the mesh material by the material or multiMaterial `id` property.
  26088. * The material `id` is a string identifying the material or the multiMaterial.
  26089. * This method returns the Mesh.
  26090. */
  26091. Mesh.prototype.setMaterialByID = function (id) {
  26092. var materials = this.getScene().materials;
  26093. var index;
  26094. for (index = materials.length - 1; index > -1; index--) {
  26095. if (materials[index].id === id) {
  26096. this.material = materials[index];
  26097. return this;
  26098. }
  26099. }
  26100. // Multi
  26101. var multiMaterials = this.getScene().multiMaterials;
  26102. for (index = multiMaterials.length - 1; index > -1; index--) {
  26103. if (multiMaterials[index].id === id) {
  26104. this.material = multiMaterials[index];
  26105. return this;
  26106. }
  26107. }
  26108. return this;
  26109. };
  26110. /**
  26111. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26112. */
  26113. Mesh.prototype.getAnimatables = function () {
  26114. var results = new Array();
  26115. if (this.material) {
  26116. results.push(this.material);
  26117. }
  26118. if (this.skeleton) {
  26119. results.push(this.skeleton);
  26120. }
  26121. return results;
  26122. };
  26123. /**
  26124. * Modifies the mesh geometry according to the passed transformation matrix.
  26125. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26126. * The mesh normals are modified accordingly the same transformation.
  26127. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26128. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26129. * Returns the Mesh.
  26130. */
  26131. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26132. // Position
  26133. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26134. return this;
  26135. }
  26136. var submeshes = this.subMeshes.splice(0);
  26137. this._resetPointsArrayCache();
  26138. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26139. var temp = new Array();
  26140. var index;
  26141. for (index = 0; index < data.length; index += 3) {
  26142. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26143. }
  26144. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26145. // Normals
  26146. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26147. return this;
  26148. }
  26149. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26150. temp = [];
  26151. for (index = 0; index < data.length; index += 3) {
  26152. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26153. }
  26154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26155. // flip faces?
  26156. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26157. this.flipFaces();
  26158. }
  26159. // Restore submeshes
  26160. this.releaseSubMeshes();
  26161. this.subMeshes = submeshes;
  26162. return this;
  26163. };
  26164. /**
  26165. * Modifies the mesh geometry according to its own current World Matrix.
  26166. * The mesh World Matrix is then reset.
  26167. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26168. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26169. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26170. * Returns the Mesh.
  26171. */
  26172. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26173. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26174. this.scaling.copyFromFloats(1, 1, 1);
  26175. this.position.copyFromFloats(0, 0, 0);
  26176. this.rotation.copyFromFloats(0, 0, 0);
  26177. //only if quaternion is already set
  26178. if (this.rotationQuaternion) {
  26179. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26180. }
  26181. this._worldMatrix = BABYLON.Matrix.Identity();
  26182. return this;
  26183. };
  26184. Object.defineProperty(Mesh.prototype, "_positions", {
  26185. // Cache
  26186. get: function () {
  26187. if (this._geometry) {
  26188. return this._geometry._positions;
  26189. }
  26190. return null;
  26191. },
  26192. enumerable: true,
  26193. configurable: true
  26194. });
  26195. Mesh.prototype._resetPointsArrayCache = function () {
  26196. if (this._geometry) {
  26197. this._geometry._resetPointsArrayCache();
  26198. }
  26199. return this;
  26200. };
  26201. Mesh.prototype._generatePointsArray = function () {
  26202. if (this._geometry) {
  26203. return this._geometry._generatePointsArray();
  26204. }
  26205. return false;
  26206. };
  26207. /**
  26208. * Returns a new Mesh object generated from the current mesh properties.
  26209. * This method must not get confused with createInstance().
  26210. * The parameter `name` is a string, the name given to the new mesh.
  26211. * The optional parameter `newParent` can be any Node object (default `null`).
  26212. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26213. * 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.
  26214. */
  26215. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26216. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26217. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26218. };
  26219. /**
  26220. * Disposes the Mesh.
  26221. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26222. * Returns nothing.
  26223. */
  26224. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26225. var _this = this;
  26226. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26227. this.morphTargetManager = null;
  26228. if (this._geometry) {
  26229. this._geometry.releaseForMesh(this, true);
  26230. }
  26231. // Sources
  26232. var meshes = this.getScene().meshes;
  26233. meshes.forEach(function (abstractMesh) {
  26234. var mesh = abstractMesh;
  26235. if (mesh._source && mesh._source === _this) {
  26236. mesh._source = null;
  26237. }
  26238. });
  26239. this._source = null;
  26240. // Instances
  26241. if (this._instancesBuffer) {
  26242. this._instancesBuffer.dispose();
  26243. this._instancesBuffer = null;
  26244. }
  26245. while (this.instances.length) {
  26246. this.instances[0].dispose();
  26247. }
  26248. // Highlight layers.
  26249. var highlightLayers = this.getScene().highlightLayers;
  26250. for (var i = 0; i < highlightLayers.length; i++) {
  26251. var highlightLayer = highlightLayers[i];
  26252. if (highlightLayer) {
  26253. highlightLayer.removeMesh(this);
  26254. highlightLayer.removeExcludedMesh(this);
  26255. }
  26256. }
  26257. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26258. };
  26259. /**
  26260. * Modifies the mesh geometry according to a displacement map.
  26261. * 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.
  26262. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26263. * This method returns nothing.
  26264. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26265. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26266. * 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.
  26267. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26268. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26269. *
  26270. * Returns the Mesh.
  26271. */
  26272. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26273. var _this = this;
  26274. var scene = this.getScene();
  26275. var onload = function (img) {
  26276. // Getting height map data
  26277. var canvas = document.createElement("canvas");
  26278. var context = canvas.getContext("2d");
  26279. var heightMapWidth = img.width;
  26280. var heightMapHeight = img.height;
  26281. canvas.width = heightMapWidth;
  26282. canvas.height = heightMapHeight;
  26283. context.drawImage(img, 0, 0);
  26284. // Create VertexData from map data
  26285. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26286. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26287. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26288. //execute success callback, if set
  26289. if (onSuccess) {
  26290. onSuccess(_this);
  26291. }
  26292. };
  26293. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26294. return this;
  26295. };
  26296. /**
  26297. * Modifies the mesh geometry according to a displacementMap buffer.
  26298. * 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.
  26299. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26300. * This method returns nothing.
  26301. * 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.
  26302. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26303. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26304. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26305. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26306. *
  26307. * Returns the Mesh.
  26308. */
  26309. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26311. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26312. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26313. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26314. return this;
  26315. }
  26316. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26317. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26318. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26319. var position = BABYLON.Vector3.Zero();
  26320. var normal = BABYLON.Vector3.Zero();
  26321. var uv = BABYLON.Vector2.Zero();
  26322. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26323. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26324. for (var index = 0; index < positions.length; index += 3) {
  26325. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26326. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26327. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26328. // Compute height
  26329. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26330. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26331. var pos = (u + v * heightMapWidth) * 4;
  26332. var r = buffer[pos] / 255.0;
  26333. var g = buffer[pos + 1] / 255.0;
  26334. var b = buffer[pos + 2] / 255.0;
  26335. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26336. normal.normalize();
  26337. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26338. position = position.add(normal);
  26339. position.toArray(positions, index);
  26340. }
  26341. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26342. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26343. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26344. return this;
  26345. };
  26346. /**
  26347. * Modify the mesh to get a flat shading rendering.
  26348. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26349. * This method returns the Mesh.
  26350. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26351. */
  26352. Mesh.prototype.convertToFlatShadedMesh = function () {
  26353. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26354. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26355. var kinds = this.getVerticesDataKinds();
  26356. var vbs = {};
  26357. var data = {};
  26358. var newdata = {};
  26359. var updatableNormals = false;
  26360. var kindIndex;
  26361. var kind;
  26362. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26363. kind = kinds[kindIndex];
  26364. var vertexBuffer = this.getVertexBuffer(kind);
  26365. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26366. updatableNormals = vertexBuffer.isUpdatable();
  26367. kinds.splice(kindIndex, 1);
  26368. kindIndex--;
  26369. continue;
  26370. }
  26371. vbs[kind] = vertexBuffer;
  26372. data[kind] = vbs[kind].getData();
  26373. newdata[kind] = [];
  26374. }
  26375. // Save previous submeshes
  26376. var previousSubmeshes = this.subMeshes.slice(0);
  26377. var indices = this.getIndices();
  26378. var totalIndices = this.getTotalIndices();
  26379. // Generating unique vertices per face
  26380. var index;
  26381. for (index = 0; index < totalIndices; index++) {
  26382. var vertexIndex = indices[index];
  26383. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26384. kind = kinds[kindIndex];
  26385. var stride = vbs[kind].getStrideSize();
  26386. for (var offset = 0; offset < stride; offset++) {
  26387. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26388. }
  26389. }
  26390. }
  26391. // Updating faces & normal
  26392. var normals = [];
  26393. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26394. for (index = 0; index < totalIndices; index += 3) {
  26395. indices[index] = index;
  26396. indices[index + 1] = index + 1;
  26397. indices[index + 2] = index + 2;
  26398. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26399. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26400. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26401. var p1p2 = p1.subtract(p2);
  26402. var p3p2 = p3.subtract(p2);
  26403. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26404. // Store same normals for every vertex
  26405. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26406. normals.push(normal.x);
  26407. normals.push(normal.y);
  26408. normals.push(normal.z);
  26409. }
  26410. }
  26411. this.setIndices(indices);
  26412. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26413. // Updating vertex buffers
  26414. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26415. kind = kinds[kindIndex];
  26416. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26417. }
  26418. // Updating submeshes
  26419. this.releaseSubMeshes();
  26420. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26421. var previousOne = previousSubmeshes[submeshIndex];
  26422. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26423. }
  26424. this.synchronizeInstances();
  26425. return this;
  26426. };
  26427. /**
  26428. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26429. * In other words, more vertices, no more indices and a single bigger VBO.
  26430. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26431. * Returns the Mesh.
  26432. */
  26433. Mesh.prototype.convertToUnIndexedMesh = function () {
  26434. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26435. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26436. var kinds = this.getVerticesDataKinds();
  26437. var vbs = {};
  26438. var data = {};
  26439. var newdata = {};
  26440. var kindIndex;
  26441. var kind;
  26442. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26443. kind = kinds[kindIndex];
  26444. var vertexBuffer = this.getVertexBuffer(kind);
  26445. vbs[kind] = vertexBuffer;
  26446. data[kind] = vbs[kind].getData();
  26447. newdata[kind] = [];
  26448. }
  26449. // Save previous submeshes
  26450. var previousSubmeshes = this.subMeshes.slice(0);
  26451. var indices = this.getIndices();
  26452. var totalIndices = this.getTotalIndices();
  26453. // Generating unique vertices per face
  26454. var index;
  26455. for (index = 0; index < totalIndices; index++) {
  26456. var vertexIndex = indices[index];
  26457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26458. kind = kinds[kindIndex];
  26459. var stride = vbs[kind].getStrideSize();
  26460. for (var offset = 0; offset < stride; offset++) {
  26461. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26462. }
  26463. }
  26464. }
  26465. // Updating indices
  26466. for (index = 0; index < totalIndices; index += 3) {
  26467. indices[index] = index;
  26468. indices[index + 1] = index + 1;
  26469. indices[index + 2] = index + 2;
  26470. }
  26471. this.setIndices(indices);
  26472. // Updating vertex buffers
  26473. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26474. kind = kinds[kindIndex];
  26475. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26476. }
  26477. // Updating submeshes
  26478. this.releaseSubMeshes();
  26479. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26480. var previousOne = previousSubmeshes[submeshIndex];
  26481. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26482. }
  26483. this._unIndexed = true;
  26484. this.synchronizeInstances();
  26485. return this;
  26486. };
  26487. /**
  26488. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26489. * This method returns the Mesh.
  26490. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26491. */
  26492. Mesh.prototype.flipFaces = function (flipNormals) {
  26493. if (flipNormals === void 0) { flipNormals = false; }
  26494. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26495. var i;
  26496. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26497. for (i = 0; i < vertex_data.normals.length; i++) {
  26498. vertex_data.normals[i] *= -1;
  26499. }
  26500. }
  26501. if (vertex_data.indices) {
  26502. var temp;
  26503. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26504. // reassign indices
  26505. temp = vertex_data.indices[i + 1];
  26506. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26507. vertex_data.indices[i + 2] = temp;
  26508. }
  26509. }
  26510. vertex_data.applyToMesh(this);
  26511. return this;
  26512. };
  26513. // Instances
  26514. /**
  26515. * Creates a new InstancedMesh object from the mesh model.
  26516. * An instance shares the same properties and the same material than its model.
  26517. * Only these properties of each instance can then be set individually :
  26518. * - position
  26519. * - rotation
  26520. * - rotationQuaternion
  26521. * - setPivotMatrix
  26522. * - scaling
  26523. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26524. * Warning : this method is not supported for Line mesh and LineSystem
  26525. */
  26526. Mesh.prototype.createInstance = function (name) {
  26527. return new BABYLON.InstancedMesh(name, this);
  26528. };
  26529. /**
  26530. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26531. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26532. * This method returns the Mesh.
  26533. */
  26534. Mesh.prototype.synchronizeInstances = function () {
  26535. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26536. var instance = this.instances[instanceIndex];
  26537. instance._syncSubMeshes();
  26538. }
  26539. return this;
  26540. };
  26541. /**
  26542. * Simplify the mesh according to the given array of settings.
  26543. * Function will return immediately and will simplify async. It returns the Mesh.
  26544. * @param settings a collection of simplification settings.
  26545. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26546. * @param type the type of simplification to run.
  26547. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26548. */
  26549. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26550. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26551. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26552. this.getScene().simplificationQueue.addTask({
  26553. settings: settings,
  26554. parallelProcessing: parallelProcessing,
  26555. mesh: this,
  26556. simplificationType: simplificationType,
  26557. successCallback: successCallback
  26558. });
  26559. return this;
  26560. };
  26561. /**
  26562. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26563. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26564. * This should be used together with the simplification to avoid disappearing triangles.
  26565. * Returns the Mesh.
  26566. * @param successCallback an optional success callback to be called after the optimization finished.
  26567. */
  26568. Mesh.prototype.optimizeIndices = function (successCallback) {
  26569. var _this = this;
  26570. var indices = this.getIndices();
  26571. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26572. if (!positions || !indices) {
  26573. return this;
  26574. }
  26575. var vectorPositions = new Array();
  26576. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26577. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26578. }
  26579. var dupes = new Array();
  26580. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26581. var realPos = vectorPositions.length - 1 - iteration;
  26582. var testedPosition = vectorPositions[realPos];
  26583. for (var j = 0; j < realPos; ++j) {
  26584. var againstPosition = vectorPositions[j];
  26585. if (testedPosition.equals(againstPosition)) {
  26586. dupes[realPos] = j;
  26587. break;
  26588. }
  26589. }
  26590. }, function () {
  26591. for (var i = 0; i < indices.length; ++i) {
  26592. indices[i] = dupes[indices[i]] || indices[i];
  26593. }
  26594. //indices are now reordered
  26595. var originalSubMeshes = _this.subMeshes.slice(0);
  26596. _this.setIndices(indices);
  26597. _this.subMeshes = originalSubMeshes;
  26598. if (successCallback) {
  26599. successCallback(_this);
  26600. }
  26601. });
  26602. return this;
  26603. };
  26604. Mesh.prototype.serialize = function (serializationObject) {
  26605. serializationObject.name = this.name;
  26606. serializationObject.id = this.id;
  26607. serializationObject.type = this.getClassName();
  26608. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26609. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26610. }
  26611. serializationObject.position = this.position.asArray();
  26612. if (this.rotationQuaternion) {
  26613. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26614. }
  26615. else if (this.rotation) {
  26616. serializationObject.rotation = this.rotation.asArray();
  26617. }
  26618. serializationObject.scaling = this.scaling.asArray();
  26619. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26620. serializationObject.isEnabled = this.isEnabled(false);
  26621. serializationObject.isVisible = this.isVisible;
  26622. serializationObject.infiniteDistance = this.infiniteDistance;
  26623. serializationObject.pickable = this.isPickable;
  26624. serializationObject.receiveShadows = this.receiveShadows;
  26625. serializationObject.billboardMode = this.billboardMode;
  26626. serializationObject.visibility = this.visibility;
  26627. serializationObject.checkCollisions = this.checkCollisions;
  26628. serializationObject.isBlocker = this.isBlocker;
  26629. // Parent
  26630. if (this.parent) {
  26631. serializationObject.parentId = this.parent.id;
  26632. }
  26633. // Geometry
  26634. serializationObject.isUnIndexed = this.isUnIndexed;
  26635. var geometry = this._geometry;
  26636. if (geometry) {
  26637. var geometryId = geometry.id;
  26638. serializationObject.geometryId = geometryId;
  26639. // SubMeshes
  26640. serializationObject.subMeshes = [];
  26641. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26642. var subMesh = this.subMeshes[subIndex];
  26643. serializationObject.subMeshes.push({
  26644. materialIndex: subMesh.materialIndex,
  26645. verticesStart: subMesh.verticesStart,
  26646. verticesCount: subMesh.verticesCount,
  26647. indexStart: subMesh.indexStart,
  26648. indexCount: subMesh.indexCount
  26649. });
  26650. }
  26651. }
  26652. // Material
  26653. if (this.material) {
  26654. serializationObject.materialId = this.material.id;
  26655. }
  26656. else {
  26657. this.material = null;
  26658. }
  26659. // Morph targets
  26660. if (this.morphTargetManager) {
  26661. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26662. }
  26663. // Skeleton
  26664. if (this.skeleton) {
  26665. serializationObject.skeletonId = this.skeleton.id;
  26666. }
  26667. // Physics
  26668. //TODO implement correct serialization for physics impostors.
  26669. var impostor = this.getPhysicsImpostor();
  26670. if (impostor) {
  26671. serializationObject.physicsMass = impostor.getParam("mass");
  26672. serializationObject.physicsFriction = impostor.getParam("friction");
  26673. serializationObject.physicsRestitution = impostor.getParam("mass");
  26674. serializationObject.physicsImpostor = impostor.type;
  26675. }
  26676. // Metadata
  26677. if (this.metadata) {
  26678. serializationObject.metadata = this.metadata;
  26679. }
  26680. // Instances
  26681. serializationObject.instances = [];
  26682. for (var index = 0; index < this.instances.length; index++) {
  26683. var instance = this.instances[index];
  26684. var serializationInstance = {
  26685. name: instance.name,
  26686. id: instance.id,
  26687. position: instance.position.asArray(),
  26688. scaling: instance.scaling.asArray()
  26689. };
  26690. if (instance.rotationQuaternion) {
  26691. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26692. }
  26693. else if (instance.rotation) {
  26694. serializationInstance.rotation = instance.rotation.asArray();
  26695. }
  26696. serializationObject.instances.push(serializationInstance);
  26697. // Animations
  26698. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26699. serializationInstance.ranges = instance.serializeAnimationRanges();
  26700. }
  26701. //
  26702. // Animations
  26703. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26704. serializationObject.ranges = this.serializeAnimationRanges();
  26705. // Layer mask
  26706. serializationObject.layerMask = this.layerMask;
  26707. // Alpha
  26708. serializationObject.alphaIndex = this.alphaIndex;
  26709. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26710. // Overlay
  26711. serializationObject.overlayAlpha = this.overlayAlpha;
  26712. serializationObject.overlayColor = this.overlayColor.asArray();
  26713. serializationObject.renderOverlay = this.renderOverlay;
  26714. // Fog
  26715. serializationObject.applyFog = this.applyFog;
  26716. // Action Manager
  26717. if (this.actionManager) {
  26718. serializationObject.actions = this.actionManager.serialize(this.name);
  26719. }
  26720. };
  26721. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26722. if (!this.geometry) {
  26723. return;
  26724. }
  26725. this._markSubMeshesAsAttributesDirty();
  26726. var morphTargetManager = this._morphTargetManager;
  26727. if (morphTargetManager && morphTargetManager.vertexCount) {
  26728. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26729. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26730. this.morphTargetManager = null;
  26731. return;
  26732. }
  26733. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26734. var morphTarget = morphTargetManager.getActiveTarget(index);
  26735. var positions = morphTarget.getPositions();
  26736. if (!positions) {
  26737. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26738. return;
  26739. }
  26740. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26741. var normals = morphTarget.getNormals();
  26742. if (normals) {
  26743. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26744. }
  26745. var tangents = morphTarget.getTangents();
  26746. if (tangents) {
  26747. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26748. }
  26749. }
  26750. }
  26751. else {
  26752. var index = 0;
  26753. // Positions
  26754. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26755. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26756. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26757. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26758. }
  26759. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26760. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26761. }
  26762. index++;
  26763. }
  26764. }
  26765. };
  26766. // Statics
  26767. /**
  26768. * Returns a new Mesh object parsed from the source provided.
  26769. * The parameter `parsedMesh` is the source.
  26770. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26771. */
  26772. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26773. var mesh;
  26774. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26775. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26776. }
  26777. else {
  26778. mesh = new Mesh(parsedMesh.name, scene);
  26779. }
  26780. mesh.id = parsedMesh.id;
  26781. if (BABYLON.Tags) {
  26782. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26783. }
  26784. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26785. if (parsedMesh.metadata !== undefined) {
  26786. mesh.metadata = parsedMesh.metadata;
  26787. }
  26788. if (parsedMesh.rotationQuaternion) {
  26789. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26790. }
  26791. else if (parsedMesh.rotation) {
  26792. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26793. }
  26794. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26795. if (parsedMesh.localMatrix) {
  26796. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26797. }
  26798. else if (parsedMesh.pivotMatrix) {
  26799. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26800. }
  26801. mesh.setEnabled(parsedMesh.isEnabled);
  26802. mesh.isVisible = parsedMesh.isVisible;
  26803. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26804. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26805. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26806. if (parsedMesh.applyFog !== undefined) {
  26807. mesh.applyFog = parsedMesh.applyFog;
  26808. }
  26809. if (parsedMesh.pickable !== undefined) {
  26810. mesh.isPickable = parsedMesh.pickable;
  26811. }
  26812. if (parsedMesh.alphaIndex !== undefined) {
  26813. mesh.alphaIndex = parsedMesh.alphaIndex;
  26814. }
  26815. mesh.receiveShadows = parsedMesh.receiveShadows;
  26816. mesh.billboardMode = parsedMesh.billboardMode;
  26817. if (parsedMesh.visibility !== undefined) {
  26818. mesh.visibility = parsedMesh.visibility;
  26819. }
  26820. mesh.checkCollisions = parsedMesh.checkCollisions;
  26821. if (parsedMesh.isBlocker !== undefined) {
  26822. mesh.isBlocker = parsedMesh.isBlocker;
  26823. }
  26824. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26825. // freezeWorldMatrix
  26826. if (parsedMesh.freezeWorldMatrix) {
  26827. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26828. }
  26829. // Parent
  26830. if (parsedMesh.parentId) {
  26831. mesh._waitingParentId = parsedMesh.parentId;
  26832. }
  26833. // Actions
  26834. if (parsedMesh.actions !== undefined) {
  26835. mesh._waitingActions = parsedMesh.actions;
  26836. }
  26837. // Overlay
  26838. if (parsedMesh.overlayAlpha !== undefined) {
  26839. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26840. }
  26841. if (parsedMesh.overlayColor !== undefined) {
  26842. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26843. }
  26844. if (parsedMesh.renderOverlay !== undefined) {
  26845. mesh.renderOverlay = parsedMesh.renderOverlay;
  26846. }
  26847. // Geometry
  26848. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26849. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26850. if (parsedMesh.delayLoadingFile) {
  26851. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26852. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26853. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26854. if (parsedMesh._binaryInfo) {
  26855. mesh._binaryInfo = parsedMesh._binaryInfo;
  26856. }
  26857. mesh._delayInfo = [];
  26858. if (parsedMesh.hasUVs) {
  26859. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26860. }
  26861. if (parsedMesh.hasUVs2) {
  26862. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26863. }
  26864. if (parsedMesh.hasUVs3) {
  26865. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26866. }
  26867. if (parsedMesh.hasUVs4) {
  26868. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26869. }
  26870. if (parsedMesh.hasUVs5) {
  26871. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26872. }
  26873. if (parsedMesh.hasUVs6) {
  26874. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26875. }
  26876. if (parsedMesh.hasColors) {
  26877. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26878. }
  26879. if (parsedMesh.hasMatricesIndices) {
  26880. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26881. }
  26882. if (parsedMesh.hasMatricesWeights) {
  26883. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26884. }
  26885. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26886. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26887. mesh._checkDelayState();
  26888. }
  26889. }
  26890. else {
  26891. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26892. }
  26893. // Material
  26894. if (parsedMesh.materialId) {
  26895. mesh.setMaterialByID(parsedMesh.materialId);
  26896. }
  26897. else {
  26898. mesh.material = null;
  26899. }
  26900. // Morph targets
  26901. if (parsedMesh.morphTargetManagerId > -1) {
  26902. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26903. }
  26904. // Skeleton
  26905. if (parsedMesh.skeletonId > -1) {
  26906. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26907. if (parsedMesh.numBoneInfluencers) {
  26908. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26909. }
  26910. }
  26911. // Animations
  26912. if (parsedMesh.animations) {
  26913. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26914. var parsedAnimation = parsedMesh.animations[animationIndex];
  26915. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26916. }
  26917. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26918. }
  26919. if (parsedMesh.autoAnimate) {
  26920. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26921. }
  26922. // Layer Mask
  26923. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26924. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26925. }
  26926. else {
  26927. mesh.layerMask = 0x0FFFFFFF;
  26928. }
  26929. // Physics
  26930. if (parsedMesh.physicsImpostor) {
  26931. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26932. mass: parsedMesh.physicsMass,
  26933. friction: parsedMesh.physicsFriction,
  26934. restitution: parsedMesh.physicsRestitution
  26935. }, scene);
  26936. }
  26937. // Instances
  26938. if (parsedMesh.instances) {
  26939. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26940. var parsedInstance = parsedMesh.instances[index];
  26941. var instance = mesh.createInstance(parsedInstance.name);
  26942. if (parsedInstance.id) {
  26943. instance.id = parsedInstance.id;
  26944. }
  26945. if (BABYLON.Tags) {
  26946. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26947. }
  26948. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26949. if (parsedInstance.parentId) {
  26950. instance._waitingParentId = parsedInstance.parentId;
  26951. }
  26952. if (parsedInstance.rotationQuaternion) {
  26953. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26954. }
  26955. else if (parsedInstance.rotation) {
  26956. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26957. }
  26958. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26959. instance.checkCollisions = mesh.checkCollisions;
  26960. if (parsedMesh.animations) {
  26961. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26962. parsedAnimation = parsedMesh.animations[animationIndex];
  26963. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26964. }
  26965. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26966. }
  26967. }
  26968. }
  26969. return mesh;
  26970. };
  26971. /**
  26972. * Creates a ribbon mesh.
  26973. * Please consider using the same method from the MeshBuilder class instead.
  26974. * 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.
  26975. *
  26976. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26977. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26978. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26979. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26980. * 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.
  26981. * 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.
  26982. * 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
  26983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26984. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26986. */
  26987. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26988. if (closeArray === void 0) { closeArray = false; }
  26989. if (updatable === void 0) { updatable = false; }
  26990. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26991. pathArray: pathArray,
  26992. closeArray: closeArray,
  26993. closePath: closePath,
  26994. offset: offset,
  26995. updatable: updatable,
  26996. sideOrientation: sideOrientation,
  26997. instance: instance
  26998. }, scene);
  26999. };
  27000. /**
  27001. * Creates a plane polygonal mesh. By default, this is a disc.
  27002. * Please consider using the same method from the MeshBuilder class instead.
  27003. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27004. * 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.
  27005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27006. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27008. */
  27009. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27010. if (scene === void 0) { scene = null; }
  27011. var options = {
  27012. radius: radius,
  27013. tessellation: tessellation,
  27014. sideOrientation: sideOrientation,
  27015. updatable: updatable
  27016. };
  27017. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27018. };
  27019. /**
  27020. * Creates a box mesh.
  27021. * Please consider using the same method from the MeshBuilder class instead.
  27022. * The parameter `size` sets the size (float) of each box side (default 1).
  27023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27026. */
  27027. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27028. if (scene === void 0) { scene = null; }
  27029. var options = {
  27030. size: size,
  27031. sideOrientation: sideOrientation,
  27032. updatable: updatable
  27033. };
  27034. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27035. };
  27036. /**
  27037. * Creates a sphere mesh.
  27038. * Please consider using the same method from the MeshBuilder class instead.
  27039. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27040. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27042. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27044. */
  27045. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27046. var options = {
  27047. segments: segments,
  27048. diameterX: diameter,
  27049. diameterY: diameter,
  27050. diameterZ: diameter,
  27051. sideOrientation: sideOrientation,
  27052. updatable: updatable
  27053. };
  27054. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27055. };
  27056. /**
  27057. * Creates a cylinder or a cone mesh.
  27058. * Please consider using the same method from the MeshBuilder class instead.
  27059. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27060. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27061. * 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.
  27062. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27063. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27067. */
  27068. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27069. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27070. if (scene !== undefined) {
  27071. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27072. updatable = scene;
  27073. }
  27074. scene = subdivisions;
  27075. subdivisions = 1;
  27076. }
  27077. var options = {
  27078. height: height,
  27079. diameterTop: diameterTop,
  27080. diameterBottom: diameterBottom,
  27081. tessellation: tessellation,
  27082. subdivisions: subdivisions,
  27083. sideOrientation: sideOrientation,
  27084. updatable: updatable
  27085. };
  27086. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27087. };
  27088. // Torus (Code from SharpDX.org)
  27089. /**
  27090. * Creates a torus mesh.
  27091. * Please consider using the same method from the MeshBuilder class instead.
  27092. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27093. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27094. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27098. */
  27099. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27100. var options = {
  27101. diameter: diameter,
  27102. thickness: thickness,
  27103. tessellation: tessellation,
  27104. sideOrientation: sideOrientation,
  27105. updatable: updatable
  27106. };
  27107. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27108. };
  27109. /**
  27110. * Creates a torus knot mesh.
  27111. * Please consider using the same method from the MeshBuilder class instead.
  27112. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27113. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27114. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27115. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27119. */
  27120. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27121. var options = {
  27122. radius: radius,
  27123. tube: tube,
  27124. radialSegments: radialSegments,
  27125. tubularSegments: tubularSegments,
  27126. p: p,
  27127. q: q,
  27128. sideOrientation: sideOrientation,
  27129. updatable: updatable
  27130. };
  27131. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27132. };
  27133. /**
  27134. * Creates a line mesh.
  27135. * Please consider using the same method from the MeshBuilder class instead.
  27136. * 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.
  27137. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27138. * The parameter `points` is an array successive Vector3.
  27139. * 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
  27140. * When updating an instance, remember that only point positions can change, not the number of points.
  27141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27142. */
  27143. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27144. if (scene === void 0) { scene = null; }
  27145. if (updatable === void 0) { updatable = false; }
  27146. if (instance === void 0) { instance = null; }
  27147. var options = {
  27148. points: points,
  27149. updatable: updatable,
  27150. instance: instance
  27151. };
  27152. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27153. };
  27154. /**
  27155. * Creates a dashed line mesh.
  27156. * Please consider using the same method from the MeshBuilder class instead.
  27157. * 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.
  27158. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27159. * The parameter `points` is an array successive Vector3.
  27160. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27161. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27162. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27163. * 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
  27164. * When updating an instance, remember that only point positions can change, not the number of points.
  27165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27166. */
  27167. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27168. if (scene === void 0) { scene = null; }
  27169. var options = {
  27170. points: points,
  27171. dashSize: dashSize,
  27172. gapSize: gapSize,
  27173. dashNb: dashNb,
  27174. updatable: updatable,
  27175. instance: instance
  27176. };
  27177. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27178. };
  27179. /**
  27180. * Creates a polygon mesh.
  27181. * Please consider using the same method from the MeshBuilder class instead.
  27182. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27183. * 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.
  27184. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27186. * Remember you can only change the shape positions, not their number when updating a polygon.
  27187. */
  27188. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27189. var options = {
  27190. shape: shape,
  27191. holes: holes,
  27192. updatable: updatable,
  27193. sideOrientation: sideOrientation
  27194. };
  27195. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27196. };
  27197. /**
  27198. * Creates an extruded polygon mesh, with depth in the Y direction.
  27199. * Please consider using the same method from the MeshBuilder class instead.
  27200. */
  27201. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27202. var options = {
  27203. shape: shape,
  27204. holes: holes,
  27205. depth: depth,
  27206. updatable: updatable,
  27207. sideOrientation: sideOrientation
  27208. };
  27209. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27210. };
  27211. /**
  27212. * Creates an extruded shape mesh.
  27213. * 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.
  27214. * Please consider using the same method from the MeshBuilder class instead.
  27215. *
  27216. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27217. * 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
  27218. * extruded along the Z axis.
  27219. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27220. * 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.
  27221. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27222. * 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
  27223. * 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
  27224. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27226. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27228. */
  27229. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27230. if (scene === void 0) { scene = null; }
  27231. var options = {
  27232. shape: shape,
  27233. path: path,
  27234. scale: scale,
  27235. rotation: rotation,
  27236. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27237. sideOrientation: sideOrientation,
  27238. instance: instance,
  27239. updatable: updatable
  27240. };
  27241. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27242. };
  27243. /**
  27244. * Creates an custom extruded shape mesh.
  27245. * 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.
  27246. * Please consider using the same method from the MeshBuilder class instead.
  27247. *
  27248. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27249. * 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
  27250. * extruded along the Z axis.
  27251. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27252. * 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
  27253. * and the distance of this point from the begining of the path :
  27254. * ```javascript
  27255. * var rotationFunction = function(i, distance) {
  27256. * // do things
  27257. * return rotationValue; }
  27258. * ```
  27259. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27260. * 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
  27261. * and the distance of this point from the begining of the path :
  27262. * ```javascript
  27263. * var scaleFunction = function(i, distance) {
  27264. * // do things
  27265. * return scaleValue;}
  27266. * ```
  27267. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27268. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27269. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27270. * 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
  27271. * 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
  27272. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27273. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27274. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27276. */
  27277. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27278. var options = {
  27279. shape: shape,
  27280. path: path,
  27281. scaleFunction: scaleFunction,
  27282. rotationFunction: rotationFunction,
  27283. ribbonCloseArray: ribbonCloseArray,
  27284. ribbonClosePath: ribbonClosePath,
  27285. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27286. sideOrientation: sideOrientation,
  27287. instance: instance,
  27288. updatable: updatable
  27289. };
  27290. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27291. };
  27292. /**
  27293. * Creates lathe mesh.
  27294. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27295. * Please consider using the same method from the MeshBuilder class instead.
  27296. * 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
  27297. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27298. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27299. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27303. */
  27304. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27305. var options = {
  27306. shape: shape,
  27307. radius: radius,
  27308. tessellation: tessellation,
  27309. sideOrientation: sideOrientation,
  27310. updatable: updatable
  27311. };
  27312. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27313. };
  27314. /**
  27315. * Creates a plane mesh.
  27316. * Please consider using the same method from the MeshBuilder class instead.
  27317. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27321. */
  27322. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27323. var options = {
  27324. size: size,
  27325. width: size,
  27326. height: size,
  27327. sideOrientation: sideOrientation,
  27328. updatable: updatable
  27329. };
  27330. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27331. };
  27332. /**
  27333. * Creates a ground mesh.
  27334. * Please consider using the same method from the MeshBuilder class instead.
  27335. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27336. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27338. */
  27339. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27340. var options = {
  27341. width: width,
  27342. height: height,
  27343. subdivisions: subdivisions,
  27344. updatable: updatable
  27345. };
  27346. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27347. };
  27348. /**
  27349. * Creates a tiled ground mesh.
  27350. * Please consider using the same method from the MeshBuilder class instead.
  27351. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27352. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27353. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27354. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27355. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27356. * numbers of subdivisions on the ground width and height of each tile.
  27357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27358. */
  27359. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27360. var options = {
  27361. xmin: xmin,
  27362. zmin: zmin,
  27363. xmax: xmax,
  27364. zmax: zmax,
  27365. subdivisions: subdivisions,
  27366. precision: precision,
  27367. updatable: updatable
  27368. };
  27369. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27370. };
  27371. /**
  27372. * Creates a ground mesh from a height map.
  27373. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27374. * Please consider using the same method from the MeshBuilder class instead.
  27375. * The parameter `url` sets the URL of the height map image resource.
  27376. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27377. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27378. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27379. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27380. * 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).
  27381. * This function is passed the newly built mesh :
  27382. * ```javascript
  27383. * function(mesh) { // do things
  27384. * return; }
  27385. * ```
  27386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27387. */
  27388. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27389. var options = {
  27390. width: width,
  27391. height: height,
  27392. subdivisions: subdivisions,
  27393. minHeight: minHeight,
  27394. maxHeight: maxHeight,
  27395. updatable: updatable,
  27396. onReady: onReady
  27397. };
  27398. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27399. };
  27400. /**
  27401. * Creates a tube mesh.
  27402. * 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.
  27403. * Please consider using the same method from the MeshBuilder class instead.
  27404. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27405. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27406. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27407. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27408. * 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.
  27409. * It must return a radius value (positive float) :
  27410. * ```javascript
  27411. * var radiusFunction = function(i, distance) {
  27412. * // do things
  27413. * return radius; }
  27414. * ```
  27415. * 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
  27416. * 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
  27417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27420. */
  27421. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27422. var options = {
  27423. path: path,
  27424. radius: radius,
  27425. tessellation: tessellation,
  27426. radiusFunction: radiusFunction,
  27427. arc: 1,
  27428. cap: cap,
  27429. updatable: updatable,
  27430. sideOrientation: sideOrientation,
  27431. instance: instance
  27432. };
  27433. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27434. };
  27435. /**
  27436. * Creates a polyhedron mesh.
  27437. * Please consider using the same method from the MeshBuilder class instead.
  27438. * 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
  27439. * to choose the wanted type.
  27440. * The parameter `size` (positive float, default 1) sets the polygon size.
  27441. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27442. * 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`.
  27443. * 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
  27444. * 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)`).
  27445. * 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
  27446. * 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.
  27447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27450. */
  27451. Mesh.CreatePolyhedron = function (name, options, scene) {
  27452. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27453. };
  27454. /**
  27455. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27456. * Please consider using the same method from the MeshBuilder class instead.
  27457. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27458. * 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`).
  27459. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27460. * 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.
  27461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27464. */
  27465. Mesh.CreateIcoSphere = function (name, options, scene) {
  27466. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27467. };
  27468. /**
  27469. * Creates a decal mesh.
  27470. * Please consider using the same method from the MeshBuilder class instead.
  27471. * 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.
  27472. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27473. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27474. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27475. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27476. */
  27477. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27478. var options = {
  27479. position: position,
  27480. normal: normal,
  27481. size: size,
  27482. angle: angle
  27483. };
  27484. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27485. };
  27486. // Skeletons
  27487. /**
  27488. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27489. */
  27490. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27491. if (!this._sourcePositions) {
  27492. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27493. if (!source) {
  27494. return this._sourcePositions;
  27495. }
  27496. this._sourcePositions = new Float32Array(source);
  27497. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27498. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27499. }
  27500. }
  27501. return this._sourcePositions;
  27502. };
  27503. /**
  27504. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27505. */
  27506. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27507. if (!this._sourceNormals) {
  27508. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27509. if (!source) {
  27510. return this._sourceNormals;
  27511. }
  27512. this._sourceNormals = new Float32Array(source);
  27513. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27514. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27515. }
  27516. }
  27517. return this._sourceNormals;
  27518. };
  27519. /**
  27520. * Updates the vertex buffer by applying transformation from the bones.
  27521. * Returns the Mesh.
  27522. *
  27523. * @param {skeleton} skeleton to apply
  27524. */
  27525. Mesh.prototype.applySkeleton = function (skeleton) {
  27526. if (!this.geometry) {
  27527. return this;
  27528. }
  27529. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27530. return this;
  27531. }
  27532. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27533. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27534. return this;
  27535. }
  27536. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27537. return this;
  27538. }
  27539. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27540. return this;
  27541. }
  27542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27543. return this;
  27544. }
  27545. if (!this._sourcePositions) {
  27546. var submeshes = this.subMeshes.slice();
  27547. this.setPositionsForCPUSkinning();
  27548. this.subMeshes = submeshes;
  27549. }
  27550. if (!this._sourceNormals) {
  27551. this.setNormalsForCPUSkinning();
  27552. }
  27553. // positionsData checks for not being Float32Array will only pass at most once
  27554. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27555. if (!positionsData) {
  27556. return this;
  27557. }
  27558. if (!(positionsData instanceof Float32Array)) {
  27559. positionsData = new Float32Array(positionsData);
  27560. }
  27561. // normalsData checks for not being Float32Array will only pass at most once
  27562. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27563. if (!normalsData) {
  27564. return this;
  27565. }
  27566. if (!(normalsData instanceof Float32Array)) {
  27567. normalsData = new Float32Array(normalsData);
  27568. }
  27569. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27570. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27571. if (!matricesWeightsData || !matricesIndicesData) {
  27572. return this;
  27573. }
  27574. var needExtras = this.numBoneInfluencers > 4;
  27575. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27576. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27577. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27578. var tempVector3 = BABYLON.Vector3.Zero();
  27579. var finalMatrix = new BABYLON.Matrix();
  27580. var tempMatrix = new BABYLON.Matrix();
  27581. var matWeightIdx = 0;
  27582. var inf;
  27583. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27584. var weight;
  27585. for (inf = 0; inf < 4; inf++) {
  27586. weight = matricesWeightsData[matWeightIdx + inf];
  27587. if (weight > 0) {
  27588. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27589. finalMatrix.addToSelf(tempMatrix);
  27590. }
  27591. else
  27592. break;
  27593. }
  27594. if (needExtras) {
  27595. for (inf = 0; inf < 4; inf++) {
  27596. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27597. if (weight > 0) {
  27598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27599. finalMatrix.addToSelf(tempMatrix);
  27600. }
  27601. else
  27602. break;
  27603. }
  27604. }
  27605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27606. tempVector3.toArray(positionsData, index);
  27607. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27608. tempVector3.toArray(normalsData, index);
  27609. finalMatrix.reset();
  27610. }
  27611. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27612. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27613. return this;
  27614. };
  27615. // Tools
  27616. /**
  27617. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27618. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27619. */
  27620. Mesh.MinMax = function (meshes) {
  27621. var minVector = null;
  27622. var maxVector = null;
  27623. meshes.forEach(function (mesh, index, array) {
  27624. var boundingInfo = mesh.getBoundingInfo();
  27625. var boundingBox = boundingInfo.boundingBox;
  27626. if (!minVector || !maxVector) {
  27627. minVector = boundingBox.minimumWorld;
  27628. maxVector = boundingBox.maximumWorld;
  27629. }
  27630. else {
  27631. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27632. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27633. }
  27634. });
  27635. if (!minVector || !maxVector) {
  27636. return {
  27637. min: BABYLON.Vector3.Zero(),
  27638. max: BABYLON.Vector3.Zero()
  27639. };
  27640. }
  27641. return {
  27642. min: minVector,
  27643. max: maxVector
  27644. };
  27645. };
  27646. /**
  27647. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27648. */
  27649. Mesh.Center = function (meshesOrMinMaxVector) {
  27650. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27651. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27652. };
  27653. /**
  27654. * Merge the array of meshes into a single mesh for performance reasons.
  27655. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27656. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27657. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27658. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27659. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27660. */
  27661. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27662. if (disposeSource === void 0) { disposeSource = true; }
  27663. var index;
  27664. if (!allow32BitsIndices) {
  27665. var totalVertices = 0;
  27666. // Counting vertices
  27667. for (index = 0; index < meshes.length; index++) {
  27668. if (meshes[index]) {
  27669. totalVertices += meshes[index].getTotalVertices();
  27670. if (totalVertices > 65536) {
  27671. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27672. return null;
  27673. }
  27674. }
  27675. }
  27676. }
  27677. // Merge
  27678. var vertexData = null;
  27679. var otherVertexData;
  27680. var indiceArray = new Array();
  27681. var source = null;
  27682. for (index = 0; index < meshes.length; index++) {
  27683. if (meshes[index]) {
  27684. meshes[index].computeWorldMatrix(true);
  27685. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27686. otherVertexData.transform(meshes[index].getWorldMatrix());
  27687. if (vertexData) {
  27688. vertexData.merge(otherVertexData);
  27689. }
  27690. else {
  27691. vertexData = otherVertexData;
  27692. source = meshes[index];
  27693. }
  27694. if (subdivideWithSubMeshes) {
  27695. indiceArray.push(meshes[index].getTotalIndices());
  27696. }
  27697. }
  27698. }
  27699. source = source;
  27700. if (!meshSubclass) {
  27701. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27702. }
  27703. vertexData.applyToMesh(meshSubclass);
  27704. // Setting properties
  27705. meshSubclass.material = source.material;
  27706. meshSubclass.checkCollisions = source.checkCollisions;
  27707. // Cleaning
  27708. if (disposeSource) {
  27709. for (index = 0; index < meshes.length; index++) {
  27710. if (meshes[index]) {
  27711. meshes[index].dispose();
  27712. }
  27713. }
  27714. }
  27715. // Subdivide
  27716. if (subdivideWithSubMeshes) {
  27717. //-- Suppresions du submesh global
  27718. meshSubclass.releaseSubMeshes();
  27719. index = 0;
  27720. var offset = 0;
  27721. //-- aplique la subdivision en fonction du tableau d'indices
  27722. while (index < indiceArray.length) {
  27723. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27724. offset += indiceArray[index];
  27725. index++;
  27726. }
  27727. }
  27728. return meshSubclass;
  27729. };
  27730. // Consts
  27731. Mesh._FRONTSIDE = 0;
  27732. Mesh._BACKSIDE = 1;
  27733. Mesh._DOUBLESIDE = 2;
  27734. Mesh._DEFAULTSIDE = 0;
  27735. Mesh._NO_CAP = 0;
  27736. Mesh._CAP_START = 1;
  27737. Mesh._CAP_END = 2;
  27738. Mesh._CAP_ALL = 3;
  27739. return Mesh;
  27740. }(BABYLON.AbstractMesh));
  27741. BABYLON.Mesh = Mesh;
  27742. })(BABYLON || (BABYLON = {}));
  27743. //# sourceMappingURL=babylon.mesh.js.map
  27744. var BABYLON;
  27745. (function (BABYLON) {
  27746. var BaseSubMesh = /** @class */ (function () {
  27747. function BaseSubMesh() {
  27748. }
  27749. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27750. get: function () {
  27751. return this._materialEffect;
  27752. },
  27753. enumerable: true,
  27754. configurable: true
  27755. });
  27756. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27757. if (defines === void 0) { defines = null; }
  27758. if (this._materialEffect === effect) {
  27759. if (!effect) {
  27760. this._materialDefines = null;
  27761. }
  27762. return;
  27763. }
  27764. this._materialDefines = defines;
  27765. this._materialEffect = effect;
  27766. };
  27767. return BaseSubMesh;
  27768. }());
  27769. BABYLON.BaseSubMesh = BaseSubMesh;
  27770. var SubMesh = /** @class */ (function (_super) {
  27771. __extends(SubMesh, _super);
  27772. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27773. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27774. var _this = _super.call(this) || this;
  27775. _this.materialIndex = materialIndex;
  27776. _this.verticesStart = verticesStart;
  27777. _this.verticesCount = verticesCount;
  27778. _this.indexStart = indexStart;
  27779. _this.indexCount = indexCount;
  27780. _this._renderId = 0;
  27781. _this._mesh = mesh;
  27782. _this._renderingMesh = renderingMesh || mesh;
  27783. mesh.subMeshes.push(_this);
  27784. _this._trianglePlanes = [];
  27785. _this._id = mesh.subMeshes.length - 1;
  27786. if (createBoundingBox) {
  27787. _this.refreshBoundingInfo();
  27788. mesh.computeWorldMatrix(true);
  27789. }
  27790. return _this;
  27791. }
  27792. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27793. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27794. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27795. };
  27796. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27797. get: function () {
  27798. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27799. },
  27800. enumerable: true,
  27801. configurable: true
  27802. });
  27803. /**
  27804. * Returns the submesh BoudingInfo object.
  27805. */
  27806. SubMesh.prototype.getBoundingInfo = function () {
  27807. if (this.IsGlobal) {
  27808. return this._mesh.getBoundingInfo();
  27809. }
  27810. return this._boundingInfo;
  27811. };
  27812. /**
  27813. * Sets the submesh BoundingInfo.
  27814. * Return the SubMesh.
  27815. */
  27816. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27817. this._boundingInfo = boundingInfo;
  27818. return this;
  27819. };
  27820. /**
  27821. * Returns the mesh of the current submesh.
  27822. */
  27823. SubMesh.prototype.getMesh = function () {
  27824. return this._mesh;
  27825. };
  27826. /**
  27827. * Returns the rendering mesh of the submesh.
  27828. */
  27829. SubMesh.prototype.getRenderingMesh = function () {
  27830. return this._renderingMesh;
  27831. };
  27832. /**
  27833. * Returns the submesh material.
  27834. */
  27835. SubMesh.prototype.getMaterial = function () {
  27836. var rootMaterial = this._renderingMesh.material;
  27837. if (rootMaterial === null || rootMaterial === undefined) {
  27838. return this._mesh.getScene().defaultMaterial;
  27839. }
  27840. else if (rootMaterial.getSubMaterial) {
  27841. var multiMaterial = rootMaterial;
  27842. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27843. if (this._currentMaterial !== effectiveMaterial) {
  27844. this._currentMaterial = effectiveMaterial;
  27845. this._materialDefines = null;
  27846. }
  27847. return effectiveMaterial;
  27848. }
  27849. return rootMaterial;
  27850. };
  27851. // Methods
  27852. /**
  27853. * Sets a new updated BoundingInfo object to the submesh.
  27854. * Returns the SubMesh.
  27855. */
  27856. SubMesh.prototype.refreshBoundingInfo = function () {
  27857. this._lastColliderWorldVertices = null;
  27858. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27859. return this;
  27860. }
  27861. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27862. if (!data) {
  27863. this._boundingInfo = this._mesh.getBoundingInfo();
  27864. return this;
  27865. }
  27866. var indices = this._renderingMesh.getIndices();
  27867. var extend;
  27868. //is this the only submesh?
  27869. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27870. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27871. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27872. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27873. }
  27874. else {
  27875. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27876. }
  27877. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27878. return this;
  27879. };
  27880. SubMesh.prototype._checkCollision = function (collider) {
  27881. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27882. return boundingInfo._checkCollision(collider);
  27883. };
  27884. /**
  27885. * Updates the submesh BoundingInfo.
  27886. * Returns the Submesh.
  27887. */
  27888. SubMesh.prototype.updateBoundingInfo = function (world) {
  27889. var boundingInfo = this.getBoundingInfo();
  27890. if (!boundingInfo) {
  27891. this.refreshBoundingInfo();
  27892. boundingInfo = this.getBoundingInfo();
  27893. }
  27894. boundingInfo.update(world);
  27895. return this;
  27896. };
  27897. /**
  27898. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27899. * Boolean returned.
  27900. */
  27901. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27902. var boundingInfo = this.getBoundingInfo();
  27903. if (!boundingInfo) {
  27904. return false;
  27905. }
  27906. return boundingInfo.isInFrustum(frustumPlanes);
  27907. };
  27908. /**
  27909. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27910. * Boolean returned.
  27911. */
  27912. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27913. var boundingInfo = this.getBoundingInfo();
  27914. if (!boundingInfo) {
  27915. return false;
  27916. }
  27917. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27918. };
  27919. /**
  27920. * Renders the submesh.
  27921. * Returns it.
  27922. */
  27923. SubMesh.prototype.render = function (enableAlphaMode) {
  27924. this._renderingMesh.render(this, enableAlphaMode);
  27925. return this;
  27926. };
  27927. /**
  27928. * Returns a new Index Buffer.
  27929. * Type returned : WebGLBuffer.
  27930. */
  27931. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27932. if (!this._linesIndexBuffer) {
  27933. var linesIndices = [];
  27934. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27935. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27936. }
  27937. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27938. this.linesIndexCount = linesIndices.length;
  27939. }
  27940. return this._linesIndexBuffer;
  27941. };
  27942. /**
  27943. * True is the passed Ray intersects the submesh bounding box.
  27944. * Boolean returned.
  27945. */
  27946. SubMesh.prototype.canIntersects = function (ray) {
  27947. var boundingInfo = this.getBoundingInfo();
  27948. if (!boundingInfo) {
  27949. return false;
  27950. }
  27951. return ray.intersectsBox(boundingInfo.boundingBox);
  27952. };
  27953. /**
  27954. * Returns an object IntersectionInfo.
  27955. */
  27956. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27957. var intersectInfo = null;
  27958. // LineMesh first as it's also a Mesh...
  27959. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27960. var lineMesh = this._mesh;
  27961. // Line test
  27962. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27963. var p0 = positions[indices[index]];
  27964. var p1 = positions[indices[index + 1]];
  27965. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27966. if (length < 0) {
  27967. continue;
  27968. }
  27969. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27970. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27971. if (fastCheck) {
  27972. break;
  27973. }
  27974. }
  27975. }
  27976. }
  27977. else {
  27978. // Triangles test
  27979. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27980. var p0 = positions[indices[index]];
  27981. var p1 = positions[indices[index + 1]];
  27982. var p2 = positions[indices[index + 2]];
  27983. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27984. if (currentIntersectInfo) {
  27985. if (currentIntersectInfo.distance < 0) {
  27986. continue;
  27987. }
  27988. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27989. intersectInfo = currentIntersectInfo;
  27990. intersectInfo.faceId = index / 3;
  27991. if (fastCheck) {
  27992. break;
  27993. }
  27994. }
  27995. }
  27996. }
  27997. }
  27998. return intersectInfo;
  27999. };
  28000. SubMesh.prototype._rebuild = function () {
  28001. if (this._linesIndexBuffer) {
  28002. this._linesIndexBuffer = null;
  28003. }
  28004. };
  28005. // Clone
  28006. /**
  28007. * Creates a new Submesh from the passed Mesh.
  28008. */
  28009. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28010. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28011. if (!this.IsGlobal) {
  28012. var boundingInfo = this.getBoundingInfo();
  28013. if (!boundingInfo) {
  28014. return result;
  28015. }
  28016. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28017. }
  28018. return result;
  28019. };
  28020. // Dispose
  28021. /**
  28022. * Disposes the Submesh.
  28023. * Returns nothing.
  28024. */
  28025. SubMesh.prototype.dispose = function () {
  28026. if (this._linesIndexBuffer) {
  28027. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28028. this._linesIndexBuffer = null;
  28029. }
  28030. // Remove from mesh
  28031. var index = this._mesh.subMeshes.indexOf(this);
  28032. this._mesh.subMeshes.splice(index, 1);
  28033. };
  28034. // Statics
  28035. /**
  28036. * Creates a new Submesh from the passed parameters :
  28037. * - materialIndex (integer) : the index of the main mesh material.
  28038. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28039. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28040. * - mesh (Mesh) : the main mesh to create the submesh from.
  28041. * - renderingMesh (optional Mesh) : rendering mesh.
  28042. */
  28043. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28044. var minVertexIndex = Number.MAX_VALUE;
  28045. var maxVertexIndex = -Number.MAX_VALUE;
  28046. renderingMesh = (renderingMesh || mesh);
  28047. var indices = renderingMesh.getIndices();
  28048. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28049. var vertexIndex = indices[index];
  28050. if (vertexIndex < minVertexIndex)
  28051. minVertexIndex = vertexIndex;
  28052. if (vertexIndex > maxVertexIndex)
  28053. maxVertexIndex = vertexIndex;
  28054. }
  28055. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28056. };
  28057. return SubMesh;
  28058. }(BaseSubMesh));
  28059. BABYLON.SubMesh = SubMesh;
  28060. })(BABYLON || (BABYLON = {}));
  28061. //# sourceMappingURL=babylon.subMesh.js.map
  28062. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28063. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28064. s = arguments[i];
  28065. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28066. t[p] = s[p];
  28067. }
  28068. return t;
  28069. };
  28070. var BABYLON;
  28071. (function (BABYLON) {
  28072. var MaterialDefines = /** @class */ (function () {
  28073. function MaterialDefines() {
  28074. this._isDirty = true;
  28075. this._areLightsDirty = true;
  28076. this._areAttributesDirty = true;
  28077. this._areTexturesDirty = true;
  28078. this._areFresnelDirty = true;
  28079. this._areMiscDirty = true;
  28080. this._areImageProcessingDirty = true;
  28081. this._normals = false;
  28082. this._uvs = false;
  28083. this._needNormals = false;
  28084. this._needUVs = false;
  28085. }
  28086. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28087. get: function () {
  28088. return this._isDirty;
  28089. },
  28090. enumerable: true,
  28091. configurable: true
  28092. });
  28093. MaterialDefines.prototype.markAsProcessed = function () {
  28094. this._isDirty = false;
  28095. this._areAttributesDirty = false;
  28096. this._areTexturesDirty = false;
  28097. this._areFresnelDirty = false;
  28098. this._areLightsDirty = false;
  28099. this._areMiscDirty = false;
  28100. this._areImageProcessingDirty = false;
  28101. };
  28102. MaterialDefines.prototype.markAsUnprocessed = function () {
  28103. this._isDirty = true;
  28104. };
  28105. MaterialDefines.prototype.markAllAsDirty = function () {
  28106. this._areTexturesDirty = true;
  28107. this._areAttributesDirty = true;
  28108. this._areLightsDirty = true;
  28109. this._areFresnelDirty = true;
  28110. this._areMiscDirty = true;
  28111. this._areImageProcessingDirty = true;
  28112. this._isDirty = true;
  28113. };
  28114. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28115. this._areImageProcessingDirty = true;
  28116. this._isDirty = true;
  28117. };
  28118. MaterialDefines.prototype.markAsLightDirty = function () {
  28119. this._areLightsDirty = true;
  28120. this._isDirty = true;
  28121. };
  28122. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28123. this._areAttributesDirty = true;
  28124. this._isDirty = true;
  28125. };
  28126. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28127. this._areTexturesDirty = true;
  28128. this._isDirty = true;
  28129. };
  28130. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28131. this._areFresnelDirty = true;
  28132. this._isDirty = true;
  28133. };
  28134. MaterialDefines.prototype.markAsMiscDirty = function () {
  28135. this._areMiscDirty = true;
  28136. this._isDirty = true;
  28137. };
  28138. MaterialDefines.prototype.rebuild = function () {
  28139. if (this._keys) {
  28140. delete this._keys;
  28141. }
  28142. this._keys = [];
  28143. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28144. var key = _a[_i];
  28145. if (key[0] === "_") {
  28146. continue;
  28147. }
  28148. this._keys.push(key);
  28149. }
  28150. };
  28151. MaterialDefines.prototype.isEqual = function (other) {
  28152. if (this._keys.length !== other._keys.length) {
  28153. return false;
  28154. }
  28155. for (var index = 0; index < this._keys.length; index++) {
  28156. var prop = this._keys[index];
  28157. if (this[prop] !== other[prop]) {
  28158. return false;
  28159. }
  28160. }
  28161. return true;
  28162. };
  28163. MaterialDefines.prototype.cloneTo = function (other) {
  28164. if (this._keys.length !== other._keys.length) {
  28165. other._keys = this._keys.slice(0);
  28166. }
  28167. for (var index = 0; index < this._keys.length; index++) {
  28168. var prop = this._keys[index];
  28169. other[prop] = this[prop];
  28170. }
  28171. };
  28172. MaterialDefines.prototype.reset = function () {
  28173. for (var index = 0; index < this._keys.length; index++) {
  28174. var prop = this._keys[index];
  28175. if (typeof (this[prop]) === "number") {
  28176. this[prop] = 0;
  28177. }
  28178. else {
  28179. this[prop] = false;
  28180. }
  28181. }
  28182. };
  28183. MaterialDefines.prototype.toString = function () {
  28184. var result = "";
  28185. for (var index = 0; index < this._keys.length; index++) {
  28186. var prop = this._keys[index];
  28187. var value = this[prop];
  28188. if (typeof (value) === "number") {
  28189. result += "#define " + prop + " " + this[prop] + "\n";
  28190. }
  28191. else if (value) {
  28192. result += "#define " + prop + "\n";
  28193. }
  28194. }
  28195. return result;
  28196. };
  28197. return MaterialDefines;
  28198. }());
  28199. BABYLON.MaterialDefines = MaterialDefines;
  28200. var Material = /** @class */ (function () {
  28201. function Material(name, scene, doNotAdd) {
  28202. this.checkReadyOnEveryCall = false;
  28203. this.checkReadyOnlyOnce = false;
  28204. this.state = "";
  28205. this.alpha = 1.0;
  28206. this._backFaceCulling = true;
  28207. this.doNotSerialize = false;
  28208. this.storeEffectOnSubMeshes = false;
  28209. /**
  28210. * An event triggered when the material is disposed.
  28211. * @type {BABYLON.Observable}
  28212. */
  28213. this.onDisposeObservable = new BABYLON.Observable();
  28214. /**
  28215. * An event triggered when the material is bound.
  28216. * @type {BABYLON.Observable}
  28217. */
  28218. this.onBindObservable = new BABYLON.Observable();
  28219. /**
  28220. * An event triggered when the material is unbound.
  28221. * @type {BABYLON.Observable}
  28222. */
  28223. this.onUnBindObservable = new BABYLON.Observable();
  28224. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28225. this._needDepthPrePass = false;
  28226. this.disableDepthWrite = false;
  28227. this.forceDepthWrite = false;
  28228. this.separateCullingPass = false;
  28229. this._fogEnabled = true;
  28230. this.pointSize = 1.0;
  28231. this.zOffset = 0;
  28232. this._wasPreviouslyReady = false;
  28233. this._fillMode = Material.TriangleFillMode;
  28234. this.name = name;
  28235. this.id = name || BABYLON.Tools.RandomId();
  28236. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28237. if (this._scene.useRightHandedSystem) {
  28238. this.sideOrientation = Material.ClockWiseSideOrientation;
  28239. }
  28240. else {
  28241. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28242. }
  28243. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28244. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28245. if (!doNotAdd) {
  28246. this._scene.materials.push(this);
  28247. }
  28248. }
  28249. Object.defineProperty(Material, "TriangleFillMode", {
  28250. get: function () {
  28251. return Material._TriangleFillMode;
  28252. },
  28253. enumerable: true,
  28254. configurable: true
  28255. });
  28256. Object.defineProperty(Material, "WireFrameFillMode", {
  28257. get: function () {
  28258. return Material._WireFrameFillMode;
  28259. },
  28260. enumerable: true,
  28261. configurable: true
  28262. });
  28263. Object.defineProperty(Material, "PointFillMode", {
  28264. get: function () {
  28265. return Material._PointFillMode;
  28266. },
  28267. enumerable: true,
  28268. configurable: true
  28269. });
  28270. Object.defineProperty(Material, "PointListDrawMode", {
  28271. get: function () {
  28272. return Material._PointListDrawMode;
  28273. },
  28274. enumerable: true,
  28275. configurable: true
  28276. });
  28277. Object.defineProperty(Material, "LineListDrawMode", {
  28278. get: function () {
  28279. return Material._LineListDrawMode;
  28280. },
  28281. enumerable: true,
  28282. configurable: true
  28283. });
  28284. Object.defineProperty(Material, "LineLoopDrawMode", {
  28285. get: function () {
  28286. return Material._LineLoopDrawMode;
  28287. },
  28288. enumerable: true,
  28289. configurable: true
  28290. });
  28291. Object.defineProperty(Material, "LineStripDrawMode", {
  28292. get: function () {
  28293. return Material._LineStripDrawMode;
  28294. },
  28295. enumerable: true,
  28296. configurable: true
  28297. });
  28298. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28299. get: function () {
  28300. return Material._TriangleStripDrawMode;
  28301. },
  28302. enumerable: true,
  28303. configurable: true
  28304. });
  28305. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28306. get: function () {
  28307. return Material._TriangleFanDrawMode;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28313. get: function () {
  28314. return Material._ClockWiseSideOrientation;
  28315. },
  28316. enumerable: true,
  28317. configurable: true
  28318. });
  28319. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28320. get: function () {
  28321. return Material._CounterClockWiseSideOrientation;
  28322. },
  28323. enumerable: true,
  28324. configurable: true
  28325. });
  28326. Object.defineProperty(Material, "TextureDirtyFlag", {
  28327. get: function () {
  28328. return Material._TextureDirtyFlag;
  28329. },
  28330. enumerable: true,
  28331. configurable: true
  28332. });
  28333. Object.defineProperty(Material, "LightDirtyFlag", {
  28334. get: function () {
  28335. return Material._LightDirtyFlag;
  28336. },
  28337. enumerable: true,
  28338. configurable: true
  28339. });
  28340. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28341. get: function () {
  28342. return Material._FresnelDirtyFlag;
  28343. },
  28344. enumerable: true,
  28345. configurable: true
  28346. });
  28347. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28348. get: function () {
  28349. return Material._AttributesDirtyFlag;
  28350. },
  28351. enumerable: true,
  28352. configurable: true
  28353. });
  28354. Object.defineProperty(Material, "MiscDirtyFlag", {
  28355. get: function () {
  28356. return Material._MiscDirtyFlag;
  28357. },
  28358. enumerable: true,
  28359. configurable: true
  28360. });
  28361. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28362. get: function () {
  28363. return this._backFaceCulling;
  28364. },
  28365. set: function (value) {
  28366. if (this._backFaceCulling === value) {
  28367. return;
  28368. }
  28369. this._backFaceCulling = value;
  28370. this.markAsDirty(Material.TextureDirtyFlag);
  28371. },
  28372. enumerable: true,
  28373. configurable: true
  28374. });
  28375. Object.defineProperty(Material.prototype, "onDispose", {
  28376. set: function (callback) {
  28377. if (this._onDisposeObserver) {
  28378. this.onDisposeObservable.remove(this._onDisposeObserver);
  28379. }
  28380. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28381. },
  28382. enumerable: true,
  28383. configurable: true
  28384. });
  28385. Object.defineProperty(Material.prototype, "onBind", {
  28386. set: function (callback) {
  28387. if (this._onBindObserver) {
  28388. this.onBindObservable.remove(this._onBindObserver);
  28389. }
  28390. this._onBindObserver = this.onBindObservable.add(callback);
  28391. },
  28392. enumerable: true,
  28393. configurable: true
  28394. });
  28395. Object.defineProperty(Material.prototype, "alphaMode", {
  28396. get: function () {
  28397. return this._alphaMode;
  28398. },
  28399. set: function (value) {
  28400. if (this._alphaMode === value) {
  28401. return;
  28402. }
  28403. this._alphaMode = value;
  28404. this.markAsDirty(Material.TextureDirtyFlag);
  28405. },
  28406. enumerable: true,
  28407. configurable: true
  28408. });
  28409. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28410. get: function () {
  28411. return this._needDepthPrePass;
  28412. },
  28413. set: function (value) {
  28414. if (this._needDepthPrePass === value) {
  28415. return;
  28416. }
  28417. this._needDepthPrePass = value;
  28418. if (this._needDepthPrePass) {
  28419. this.checkReadyOnEveryCall = true;
  28420. }
  28421. },
  28422. enumerable: true,
  28423. configurable: true
  28424. });
  28425. Object.defineProperty(Material.prototype, "fogEnabled", {
  28426. get: function () {
  28427. return this._fogEnabled;
  28428. },
  28429. set: function (value) {
  28430. if (this._fogEnabled === value) {
  28431. return;
  28432. }
  28433. this._fogEnabled = value;
  28434. this.markAsDirty(Material.MiscDirtyFlag);
  28435. },
  28436. enumerable: true,
  28437. configurable: true
  28438. });
  28439. Object.defineProperty(Material.prototype, "wireframe", {
  28440. get: function () {
  28441. return this._fillMode === Material.WireFrameFillMode;
  28442. },
  28443. set: function (value) {
  28444. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28445. },
  28446. enumerable: true,
  28447. configurable: true
  28448. });
  28449. Object.defineProperty(Material.prototype, "pointsCloud", {
  28450. get: function () {
  28451. return this._fillMode === Material.PointFillMode;
  28452. },
  28453. set: function (value) {
  28454. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28455. },
  28456. enumerable: true,
  28457. configurable: true
  28458. });
  28459. Object.defineProperty(Material.prototype, "fillMode", {
  28460. get: function () {
  28461. return this._fillMode;
  28462. },
  28463. set: function (value) {
  28464. if (this._fillMode === value) {
  28465. return;
  28466. }
  28467. this._fillMode = value;
  28468. this.markAsDirty(Material.MiscDirtyFlag);
  28469. },
  28470. enumerable: true,
  28471. configurable: true
  28472. });
  28473. /**
  28474. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28475. * subclasses should override adding information pertainent to themselves
  28476. */
  28477. Material.prototype.toString = function (fullDetails) {
  28478. var ret = "Name: " + this.name;
  28479. if (fullDetails) {
  28480. }
  28481. return ret;
  28482. };
  28483. /**
  28484. * Child classes can use it to update shaders
  28485. */
  28486. Material.prototype.getClassName = function () {
  28487. return "Material";
  28488. };
  28489. Object.defineProperty(Material.prototype, "isFrozen", {
  28490. get: function () {
  28491. return this.checkReadyOnlyOnce;
  28492. },
  28493. enumerable: true,
  28494. configurable: true
  28495. });
  28496. Material.prototype.freeze = function () {
  28497. this.checkReadyOnlyOnce = true;
  28498. };
  28499. Material.prototype.unfreeze = function () {
  28500. this.checkReadyOnlyOnce = false;
  28501. };
  28502. Material.prototype.isReady = function (mesh, useInstances) {
  28503. return true;
  28504. };
  28505. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28506. return false;
  28507. };
  28508. Material.prototype.getEffect = function () {
  28509. return this._effect;
  28510. };
  28511. Material.prototype.getScene = function () {
  28512. return this._scene;
  28513. };
  28514. Material.prototype.needAlphaBlending = function () {
  28515. return (this.alpha < 1.0);
  28516. };
  28517. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28518. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28519. };
  28520. Material.prototype.needAlphaTesting = function () {
  28521. return false;
  28522. };
  28523. Material.prototype.getAlphaTestTexture = function () {
  28524. return null;
  28525. };
  28526. Material.prototype.markDirty = function () {
  28527. this._wasPreviouslyReady = false;
  28528. };
  28529. Material.prototype._preBind = function (effect, overrideOrientation) {
  28530. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28531. var engine = this._scene.getEngine();
  28532. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28533. var reverse = orientation === Material.ClockWiseSideOrientation;
  28534. engine.enableEffect(effect ? effect : this._effect);
  28535. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28536. return reverse;
  28537. };
  28538. Material.prototype.bind = function (world, mesh) {
  28539. };
  28540. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28541. };
  28542. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28543. };
  28544. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28545. sceneUbo.bindToEffect(effect, "Scene");
  28546. };
  28547. Material.prototype.bindView = function (effect) {
  28548. if (!this._useUBO) {
  28549. effect.setMatrix("view", this.getScene().getViewMatrix());
  28550. }
  28551. else {
  28552. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28553. }
  28554. };
  28555. Material.prototype.bindViewProjection = function (effect) {
  28556. if (!this._useUBO) {
  28557. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28558. }
  28559. else {
  28560. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28561. }
  28562. };
  28563. Material.prototype._afterBind = function (mesh) {
  28564. this._scene._cachedMaterial = this;
  28565. if (mesh) {
  28566. this._scene._cachedVisibility = mesh.visibility;
  28567. }
  28568. else {
  28569. this._scene._cachedVisibility = 1;
  28570. }
  28571. if (mesh) {
  28572. this.onBindObservable.notifyObservers(mesh);
  28573. }
  28574. if (this.disableDepthWrite) {
  28575. var engine = this._scene.getEngine();
  28576. this._cachedDepthWriteState = engine.getDepthWrite();
  28577. engine.setDepthWrite(false);
  28578. }
  28579. };
  28580. Material.prototype.unbind = function () {
  28581. this.onUnBindObservable.notifyObservers(this);
  28582. if (this.disableDepthWrite) {
  28583. var engine = this._scene.getEngine();
  28584. engine.setDepthWrite(this._cachedDepthWriteState);
  28585. }
  28586. };
  28587. Material.prototype.getActiveTextures = function () {
  28588. return [];
  28589. };
  28590. Material.prototype.hasTexture = function (texture) {
  28591. return false;
  28592. };
  28593. Material.prototype.clone = function (name) {
  28594. return null;
  28595. };
  28596. Material.prototype.getBindedMeshes = function () {
  28597. var result = new Array();
  28598. for (var index = 0; index < this._scene.meshes.length; index++) {
  28599. var mesh = this._scene.meshes[index];
  28600. if (mesh.material === this) {
  28601. result.push(mesh);
  28602. }
  28603. }
  28604. return result;
  28605. };
  28606. /**
  28607. * Force shader compilation including textures ready check
  28608. */
  28609. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28610. var _this = this;
  28611. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28612. var subMesh = new BABYLON.BaseSubMesh();
  28613. var scene = this.getScene();
  28614. var engine = scene.getEngine();
  28615. var checkReady = function () {
  28616. if (!_this._scene || !_this._scene.getEngine()) {
  28617. return;
  28618. }
  28619. if (subMesh._materialDefines) {
  28620. subMesh._materialDefines._renderId = -1;
  28621. }
  28622. var alphaTestState = engine.getAlphaTesting();
  28623. var clipPlaneState = scene.clipPlane;
  28624. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28625. if (localOptions.clipPlane) {
  28626. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28627. }
  28628. if (_this.storeEffectOnSubMeshes) {
  28629. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28630. if (onCompiled) {
  28631. onCompiled(_this);
  28632. }
  28633. }
  28634. else {
  28635. setTimeout(checkReady, 16);
  28636. }
  28637. }
  28638. else {
  28639. if (_this.isReady(mesh)) {
  28640. if (onCompiled) {
  28641. onCompiled(_this);
  28642. }
  28643. }
  28644. else {
  28645. setTimeout(checkReady, 16);
  28646. }
  28647. }
  28648. engine.setAlphaTesting(alphaTestState);
  28649. if (options && options.clipPlane) {
  28650. scene.clipPlane = clipPlaneState;
  28651. }
  28652. };
  28653. checkReady();
  28654. };
  28655. Material.prototype.markAsDirty = function (flag) {
  28656. if (flag & Material.TextureDirtyFlag) {
  28657. this._markAllSubMeshesAsTexturesDirty();
  28658. }
  28659. if (flag & Material.LightDirtyFlag) {
  28660. this._markAllSubMeshesAsLightsDirty();
  28661. }
  28662. if (flag & Material.FresnelDirtyFlag) {
  28663. this._markAllSubMeshesAsFresnelDirty();
  28664. }
  28665. if (flag & Material.AttributesDirtyFlag) {
  28666. this._markAllSubMeshesAsAttributesDirty();
  28667. }
  28668. if (flag & Material.MiscDirtyFlag) {
  28669. this._markAllSubMeshesAsMiscDirty();
  28670. }
  28671. this.getScene().resetCachedMaterial();
  28672. };
  28673. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28674. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28675. var mesh = _a[_i];
  28676. if (!mesh.subMeshes) {
  28677. continue;
  28678. }
  28679. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28680. var subMesh = _c[_b];
  28681. if (subMesh.getMaterial() !== this) {
  28682. continue;
  28683. }
  28684. if (!subMesh._materialDefines) {
  28685. continue;
  28686. }
  28687. func(subMesh._materialDefines);
  28688. }
  28689. }
  28690. };
  28691. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28692. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28693. };
  28694. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28695. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28696. };
  28697. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28698. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28699. };
  28700. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28701. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28702. };
  28703. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28704. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28705. };
  28706. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28707. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28708. };
  28709. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28710. // Animations
  28711. this.getScene().stopAnimation(this);
  28712. // Remove from scene
  28713. var index = this._scene.materials.indexOf(this);
  28714. if (index >= 0) {
  28715. this._scene.materials.splice(index, 1);
  28716. }
  28717. // Remove from meshes
  28718. for (index = 0; index < this._scene.meshes.length; index++) {
  28719. var mesh = this._scene.meshes[index];
  28720. if (mesh.material === this) {
  28721. mesh.material = null;
  28722. if (mesh.geometry) {
  28723. var geometry = (mesh.geometry);
  28724. if (this.storeEffectOnSubMeshes) {
  28725. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28726. var subMesh = _a[_i];
  28727. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28728. if (forceDisposeEffect && subMesh._materialEffect) {
  28729. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28730. }
  28731. }
  28732. }
  28733. else {
  28734. geometry._releaseVertexArrayObject(this._effect);
  28735. }
  28736. }
  28737. }
  28738. }
  28739. this._uniformBuffer.dispose();
  28740. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28741. if (forceDisposeEffect && this._effect) {
  28742. if (!this.storeEffectOnSubMeshes) {
  28743. this._scene.getEngine()._releaseEffect(this._effect);
  28744. }
  28745. this._effect = null;
  28746. }
  28747. // Callback
  28748. this.onDisposeObservable.notifyObservers(this);
  28749. this.onDisposeObservable.clear();
  28750. this.onBindObservable.clear();
  28751. this.onUnBindObservable.clear();
  28752. };
  28753. Material.prototype.serialize = function () {
  28754. return BABYLON.SerializationHelper.Serialize(this);
  28755. };
  28756. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28757. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28758. multiMaterial.id = parsedMultiMaterial.id;
  28759. if (BABYLON.Tags) {
  28760. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28761. }
  28762. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28763. var subMatId = parsedMultiMaterial.materials[matIndex];
  28764. if (subMatId) {
  28765. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28766. }
  28767. else {
  28768. multiMaterial.subMaterials.push(null);
  28769. }
  28770. }
  28771. return multiMaterial;
  28772. };
  28773. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28774. if (!parsedMaterial.customType) {
  28775. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28776. }
  28777. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28778. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28779. if (!BABYLON.LegacyPBRMaterial) {
  28780. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28781. return;
  28782. }
  28783. }
  28784. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28785. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28786. ;
  28787. };
  28788. // Triangle views
  28789. Material._TriangleFillMode = 0;
  28790. Material._WireFrameFillMode = 1;
  28791. Material._PointFillMode = 2;
  28792. // Draw modes
  28793. Material._PointListDrawMode = 3;
  28794. Material._LineListDrawMode = 4;
  28795. Material._LineLoopDrawMode = 5;
  28796. Material._LineStripDrawMode = 6;
  28797. Material._TriangleStripDrawMode = 7;
  28798. Material._TriangleFanDrawMode = 8;
  28799. Material._ClockWiseSideOrientation = 0;
  28800. Material._CounterClockWiseSideOrientation = 1;
  28801. Material._TextureDirtyFlag = 1;
  28802. Material._LightDirtyFlag = 2;
  28803. Material._FresnelDirtyFlag = 4;
  28804. Material._AttributesDirtyFlag = 8;
  28805. Material._MiscDirtyFlag = 16;
  28806. __decorate([
  28807. BABYLON.serialize()
  28808. ], Material.prototype, "id", void 0);
  28809. __decorate([
  28810. BABYLON.serialize()
  28811. ], Material.prototype, "name", void 0);
  28812. __decorate([
  28813. BABYLON.serialize()
  28814. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28815. __decorate([
  28816. BABYLON.serialize()
  28817. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28818. __decorate([
  28819. BABYLON.serialize()
  28820. ], Material.prototype, "state", void 0);
  28821. __decorate([
  28822. BABYLON.serialize()
  28823. ], Material.prototype, "alpha", void 0);
  28824. __decorate([
  28825. BABYLON.serialize("backFaceCulling")
  28826. ], Material.prototype, "_backFaceCulling", void 0);
  28827. __decorate([
  28828. BABYLON.serialize()
  28829. ], Material.prototype, "sideOrientation", void 0);
  28830. __decorate([
  28831. BABYLON.serialize("alphaMode")
  28832. ], Material.prototype, "_alphaMode", void 0);
  28833. __decorate([
  28834. BABYLON.serialize()
  28835. ], Material.prototype, "_needDepthPrePass", void 0);
  28836. __decorate([
  28837. BABYLON.serialize()
  28838. ], Material.prototype, "disableDepthWrite", void 0);
  28839. __decorate([
  28840. BABYLON.serialize()
  28841. ], Material.prototype, "forceDepthWrite", void 0);
  28842. __decorate([
  28843. BABYLON.serialize()
  28844. ], Material.prototype, "separateCullingPass", void 0);
  28845. __decorate([
  28846. BABYLON.serialize("fogEnabled")
  28847. ], Material.prototype, "_fogEnabled", void 0);
  28848. __decorate([
  28849. BABYLON.serialize()
  28850. ], Material.prototype, "pointSize", void 0);
  28851. __decorate([
  28852. BABYLON.serialize()
  28853. ], Material.prototype, "zOffset", void 0);
  28854. __decorate([
  28855. BABYLON.serialize()
  28856. ], Material.prototype, "wireframe", null);
  28857. __decorate([
  28858. BABYLON.serialize()
  28859. ], Material.prototype, "pointsCloud", null);
  28860. __decorate([
  28861. BABYLON.serialize()
  28862. ], Material.prototype, "fillMode", null);
  28863. return Material;
  28864. }());
  28865. BABYLON.Material = Material;
  28866. })(BABYLON || (BABYLON = {}));
  28867. //# sourceMappingURL=babylon.material.js.map
  28868. var BABYLON;
  28869. (function (BABYLON) {
  28870. var UniformBuffer = /** @class */ (function () {
  28871. /**
  28872. * Uniform buffer objects.
  28873. *
  28874. * Handles blocks of uniform on the GPU.
  28875. *
  28876. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28877. *
  28878. * For more information, please refer to :
  28879. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28880. */
  28881. function UniformBuffer(engine, data, dynamic) {
  28882. this._engine = engine;
  28883. this._noUBO = !engine.supportsUniformBuffers;
  28884. this._dynamic = dynamic;
  28885. this._data = data || [];
  28886. this._uniformLocations = {};
  28887. this._uniformSizes = {};
  28888. this._uniformLocationPointer = 0;
  28889. this._needSync = false;
  28890. if (this._noUBO) {
  28891. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28892. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28893. this.updateFloat = this._updateFloatForEffect;
  28894. this.updateFloat2 = this._updateFloat2ForEffect;
  28895. this.updateFloat3 = this._updateFloat3ForEffect;
  28896. this.updateFloat4 = this._updateFloat4ForEffect;
  28897. this.updateMatrix = this._updateMatrixForEffect;
  28898. this.updateVector3 = this._updateVector3ForEffect;
  28899. this.updateVector4 = this._updateVector4ForEffect;
  28900. this.updateColor3 = this._updateColor3ForEffect;
  28901. this.updateColor4 = this._updateColor4ForEffect;
  28902. }
  28903. else {
  28904. this._engine._uniformBuffers.push(this);
  28905. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28906. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28907. this.updateFloat = this._updateFloatForUniform;
  28908. this.updateFloat2 = this._updateFloat2ForUniform;
  28909. this.updateFloat3 = this._updateFloat3ForUniform;
  28910. this.updateFloat4 = this._updateFloat4ForUniform;
  28911. this.updateMatrix = this._updateMatrixForUniform;
  28912. this.updateVector3 = this._updateVector3ForUniform;
  28913. this.updateVector4 = this._updateVector4ForUniform;
  28914. this.updateColor3 = this._updateColor3ForUniform;
  28915. this.updateColor4 = this._updateColor4ForUniform;
  28916. }
  28917. }
  28918. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28919. // Properties
  28920. /**
  28921. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28922. * or just falling back on setUniformXXX calls.
  28923. */
  28924. get: function () {
  28925. return !this._noUBO;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28931. /**
  28932. * Indicates if the WebGL underlying uniform buffer is in sync
  28933. * with the javascript cache data.
  28934. */
  28935. get: function () {
  28936. return !this._needSync;
  28937. },
  28938. enumerable: true,
  28939. configurable: true
  28940. });
  28941. /**
  28942. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28943. * Also, a dynamic UniformBuffer will disable cache verification and always
  28944. * update the underlying WebGL uniform buffer to the GPU.
  28945. */
  28946. UniformBuffer.prototype.isDynamic = function () {
  28947. return this._dynamic !== undefined;
  28948. };
  28949. /**
  28950. * The data cache on JS side.
  28951. */
  28952. UniformBuffer.prototype.getData = function () {
  28953. return this._bufferData;
  28954. };
  28955. /**
  28956. * The underlying WebGL Uniform buffer.
  28957. */
  28958. UniformBuffer.prototype.getBuffer = function () {
  28959. return this._buffer;
  28960. };
  28961. /**
  28962. * std140 layout specifies how to align data within an UBO structure.
  28963. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28964. * for specs.
  28965. */
  28966. UniformBuffer.prototype._fillAlignment = function (size) {
  28967. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28968. // and 4x4 matrices
  28969. // TODO : change if other types are used
  28970. var alignment;
  28971. if (size <= 2) {
  28972. alignment = size;
  28973. }
  28974. else {
  28975. alignment = 4;
  28976. }
  28977. if ((this._uniformLocationPointer % alignment) !== 0) {
  28978. var oldPointer = this._uniformLocationPointer;
  28979. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28980. var diff = this._uniformLocationPointer - oldPointer;
  28981. for (var i = 0; i < diff; i++) {
  28982. this._data.push(0);
  28983. }
  28984. }
  28985. };
  28986. /**
  28987. * Adds an uniform in the buffer.
  28988. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28989. * for the layout to be correct !
  28990. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28991. * @param {number|number[]} size Data size, or data directly.
  28992. */
  28993. UniformBuffer.prototype.addUniform = function (name, size) {
  28994. if (this._noUBO) {
  28995. return;
  28996. }
  28997. if (this._uniformLocations[name] !== undefined) {
  28998. // Already existing uniform
  28999. return;
  29000. }
  29001. // This function must be called in the order of the shader layout !
  29002. // size can be the size of the uniform, or data directly
  29003. var data;
  29004. if (size instanceof Array) {
  29005. data = size;
  29006. size = data.length;
  29007. }
  29008. else {
  29009. size = size;
  29010. data = [];
  29011. // Fill with zeros
  29012. for (var i = 0; i < size; i++) {
  29013. data.push(0);
  29014. }
  29015. }
  29016. this._fillAlignment(size);
  29017. this._uniformSizes[name] = size;
  29018. this._uniformLocations[name] = this._uniformLocationPointer;
  29019. this._uniformLocationPointer += size;
  29020. for (var i = 0; i < size; i++) {
  29021. this._data.push(data[i]);
  29022. }
  29023. this._needSync = true;
  29024. };
  29025. /**
  29026. * Wrapper for addUniform.
  29027. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29028. * @param {Matrix} mat A 4x4 matrix.
  29029. */
  29030. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29031. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29032. };
  29033. /**
  29034. * Wrapper for addUniform.
  29035. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29036. * @param {number} x
  29037. * @param {number} y
  29038. */
  29039. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29040. var temp = [x, y];
  29041. this.addUniform(name, temp);
  29042. };
  29043. /**
  29044. * Wrapper for addUniform.
  29045. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29046. * @param {number} x
  29047. * @param {number} y
  29048. * @param {number} z
  29049. */
  29050. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29051. var temp = [x, y, z];
  29052. this.addUniform(name, temp);
  29053. };
  29054. /**
  29055. * Wrapper for addUniform.
  29056. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29057. * @param {Color3} color
  29058. */
  29059. UniformBuffer.prototype.addColor3 = function (name, color) {
  29060. var temp = new Array();
  29061. color.toArray(temp);
  29062. this.addUniform(name, temp);
  29063. };
  29064. /**
  29065. * Wrapper for addUniform.
  29066. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29067. * @param {Color3} color
  29068. * @param {number} alpha
  29069. */
  29070. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29071. var temp = new Array();
  29072. color.toArray(temp);
  29073. temp.push(alpha);
  29074. this.addUniform(name, temp);
  29075. };
  29076. /**
  29077. * Wrapper for addUniform.
  29078. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29079. * @param {Vector3} vector
  29080. */
  29081. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29082. var temp = new Array();
  29083. vector.toArray(temp);
  29084. this.addUniform(name, temp);
  29085. };
  29086. /**
  29087. * Wrapper for addUniform.
  29088. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29089. */
  29090. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29091. this.addUniform(name, 12);
  29092. };
  29093. /**
  29094. * Wrapper for addUniform.
  29095. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29096. */
  29097. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29098. this.addUniform(name, 8);
  29099. };
  29100. /**
  29101. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29102. */
  29103. UniformBuffer.prototype.create = function () {
  29104. if (this._noUBO) {
  29105. return;
  29106. }
  29107. if (this._buffer) {
  29108. return; // nothing to do
  29109. }
  29110. // See spec, alignment must be filled as a vec4
  29111. this._fillAlignment(4);
  29112. this._bufferData = new Float32Array(this._data);
  29113. this._rebuild();
  29114. this._needSync = true;
  29115. };
  29116. UniformBuffer.prototype._rebuild = function () {
  29117. if (this._noUBO) {
  29118. return;
  29119. }
  29120. if (this._dynamic) {
  29121. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29122. }
  29123. else {
  29124. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29125. }
  29126. };
  29127. /**
  29128. * Updates the WebGL Uniform Buffer on the GPU.
  29129. * If the `dynamic` flag is set to true, no cache comparison is done.
  29130. * Otherwise, the buffer will be updated only if the cache differs.
  29131. */
  29132. UniformBuffer.prototype.update = function () {
  29133. if (!this._buffer) {
  29134. this.create();
  29135. return;
  29136. }
  29137. if (!this._dynamic && !this._needSync) {
  29138. return;
  29139. }
  29140. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29141. this._needSync = false;
  29142. };
  29143. /**
  29144. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29145. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29146. * @param {number[]|Float32Array} data Flattened data
  29147. * @param {number} size Size of the data.
  29148. */
  29149. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29150. var location = this._uniformLocations[uniformName];
  29151. if (location === undefined) {
  29152. if (this._buffer) {
  29153. // Cannot add an uniform if the buffer is already created
  29154. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29155. return;
  29156. }
  29157. this.addUniform(uniformName, size);
  29158. location = this._uniformLocations[uniformName];
  29159. }
  29160. if (!this._buffer) {
  29161. this.create();
  29162. }
  29163. if (!this._dynamic) {
  29164. // Cache for static uniform buffers
  29165. var changed = false;
  29166. for (var i = 0; i < size; i++) {
  29167. if (this._bufferData[location + i] !== data[i]) {
  29168. changed = true;
  29169. this._bufferData[location + i] = data[i];
  29170. }
  29171. }
  29172. this._needSync = this._needSync || changed;
  29173. }
  29174. else {
  29175. // No cache for dynamic
  29176. for (var i = 0; i < size; i++) {
  29177. this._bufferData[location + i] = data[i];
  29178. }
  29179. }
  29180. };
  29181. // Update methods
  29182. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29183. // To match std140, matrix must be realigned
  29184. for (var i = 0; i < 3; i++) {
  29185. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29186. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29187. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29188. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29189. }
  29190. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29191. };
  29192. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29193. this._currentEffect.setMatrix3x3(name, matrix);
  29194. };
  29195. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29196. this._currentEffect.setMatrix2x2(name, matrix);
  29197. };
  29198. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29199. // To match std140, matrix must be realigned
  29200. for (var i = 0; i < 2; i++) {
  29201. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29202. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29203. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29204. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29205. }
  29206. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29207. };
  29208. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29209. this._currentEffect.setFloat(name, x);
  29210. };
  29211. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29212. UniformBuffer._tempBuffer[0] = x;
  29213. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29214. };
  29215. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29216. if (suffix === void 0) { suffix = ""; }
  29217. this._currentEffect.setFloat2(name + suffix, x, y);
  29218. };
  29219. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29220. if (suffix === void 0) { suffix = ""; }
  29221. UniformBuffer._tempBuffer[0] = x;
  29222. UniformBuffer._tempBuffer[1] = y;
  29223. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29224. };
  29225. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29226. if (suffix === void 0) { suffix = ""; }
  29227. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29228. };
  29229. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29230. if (suffix === void 0) { suffix = ""; }
  29231. UniformBuffer._tempBuffer[0] = x;
  29232. UniformBuffer._tempBuffer[1] = y;
  29233. UniformBuffer._tempBuffer[2] = z;
  29234. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29235. };
  29236. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29237. if (suffix === void 0) { suffix = ""; }
  29238. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29239. };
  29240. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29241. if (suffix === void 0) { suffix = ""; }
  29242. UniformBuffer._tempBuffer[0] = x;
  29243. UniformBuffer._tempBuffer[1] = y;
  29244. UniformBuffer._tempBuffer[2] = z;
  29245. UniformBuffer._tempBuffer[3] = w;
  29246. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29247. };
  29248. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29249. this._currentEffect.setMatrix(name, mat);
  29250. };
  29251. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29252. this.updateUniform(name, mat.toArray(), 16);
  29253. };
  29254. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29255. this._currentEffect.setVector3(name, vector);
  29256. };
  29257. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29258. vector.toArray(UniformBuffer._tempBuffer);
  29259. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29260. };
  29261. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29262. this._currentEffect.setVector4(name, vector);
  29263. };
  29264. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29265. vector.toArray(UniformBuffer._tempBuffer);
  29266. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29267. };
  29268. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29269. if (suffix === void 0) { suffix = ""; }
  29270. this._currentEffect.setColor3(name + suffix, color);
  29271. };
  29272. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29273. if (suffix === void 0) { suffix = ""; }
  29274. color.toArray(UniformBuffer._tempBuffer);
  29275. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29276. };
  29277. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29278. if (suffix === void 0) { suffix = ""; }
  29279. this._currentEffect.setColor4(name + suffix, color, alpha);
  29280. };
  29281. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29282. if (suffix === void 0) { suffix = ""; }
  29283. color.toArray(UniformBuffer._tempBuffer);
  29284. UniformBuffer._tempBuffer[3] = alpha;
  29285. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29286. };
  29287. /**
  29288. * Sets a sampler uniform on the effect.
  29289. * @param {string} name Name of the sampler.
  29290. * @param {Texture} texture
  29291. */
  29292. UniformBuffer.prototype.setTexture = function (name, texture) {
  29293. this._currentEffect.setTexture(name, texture);
  29294. };
  29295. /**
  29296. * Directly updates the value of the uniform in the cache AND on the GPU.
  29297. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29298. * @param {number[]|Float32Array} data Flattened data
  29299. */
  29300. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29301. this.updateUniform(uniformName, data, data.length);
  29302. this.update();
  29303. };
  29304. /**
  29305. * Binds this uniform buffer to an effect.
  29306. * @param {Effect} effect
  29307. * @param {string} name Name of the uniform block in the shader.
  29308. */
  29309. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29310. this._currentEffect = effect;
  29311. if (this._noUBO || !this._buffer) {
  29312. return;
  29313. }
  29314. effect.bindUniformBuffer(this._buffer, name);
  29315. };
  29316. /**
  29317. * Disposes the uniform buffer.
  29318. */
  29319. UniformBuffer.prototype.dispose = function () {
  29320. if (this._noUBO) {
  29321. return;
  29322. }
  29323. var index = this._engine._uniformBuffers.indexOf(this);
  29324. if (index !== -1) {
  29325. this._engine._uniformBuffers.splice(index, 1);
  29326. }
  29327. if (!this._buffer) {
  29328. return;
  29329. }
  29330. if (this._engine._releaseBuffer(this._buffer)) {
  29331. this._buffer = null;
  29332. }
  29333. };
  29334. // Pool for avoiding memory leaks
  29335. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29336. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29337. return UniformBuffer;
  29338. }());
  29339. BABYLON.UniformBuffer = UniformBuffer;
  29340. })(BABYLON || (BABYLON = {}));
  29341. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29342. var BABYLON;
  29343. (function (BABYLON) {
  29344. var VertexData = /** @class */ (function () {
  29345. function VertexData() {
  29346. }
  29347. VertexData.prototype.set = function (data, kind) {
  29348. switch (kind) {
  29349. case BABYLON.VertexBuffer.PositionKind:
  29350. this.positions = data;
  29351. break;
  29352. case BABYLON.VertexBuffer.NormalKind:
  29353. this.normals = data;
  29354. break;
  29355. case BABYLON.VertexBuffer.TangentKind:
  29356. this.tangents = data;
  29357. break;
  29358. case BABYLON.VertexBuffer.UVKind:
  29359. this.uvs = data;
  29360. break;
  29361. case BABYLON.VertexBuffer.UV2Kind:
  29362. this.uvs2 = data;
  29363. break;
  29364. case BABYLON.VertexBuffer.UV3Kind:
  29365. this.uvs3 = data;
  29366. break;
  29367. case BABYLON.VertexBuffer.UV4Kind:
  29368. this.uvs4 = data;
  29369. break;
  29370. case BABYLON.VertexBuffer.UV5Kind:
  29371. this.uvs5 = data;
  29372. break;
  29373. case BABYLON.VertexBuffer.UV6Kind:
  29374. this.uvs6 = data;
  29375. break;
  29376. case BABYLON.VertexBuffer.ColorKind:
  29377. this.colors = data;
  29378. break;
  29379. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29380. this.matricesIndices = data;
  29381. break;
  29382. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29383. this.matricesWeights = data;
  29384. break;
  29385. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29386. this.matricesIndicesExtra = data;
  29387. break;
  29388. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29389. this.matricesWeightsExtra = data;
  29390. break;
  29391. }
  29392. };
  29393. /**
  29394. * Associates the vertexData to the passed Mesh.
  29395. * Sets it as updatable or not (default `false`).
  29396. * Returns the VertexData.
  29397. */
  29398. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29399. this._applyTo(mesh, updatable);
  29400. return this;
  29401. };
  29402. /**
  29403. * Associates the vertexData to the passed Geometry.
  29404. * Sets it as updatable or not (default `false`).
  29405. * Returns the VertexData.
  29406. */
  29407. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29408. this._applyTo(geometry, updatable);
  29409. return this;
  29410. };
  29411. /**
  29412. * Updates the associated mesh.
  29413. * Returns the VertexData.
  29414. */
  29415. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29416. this._update(mesh);
  29417. return this;
  29418. };
  29419. /**
  29420. * Updates the associated geometry.
  29421. * Returns the VertexData.
  29422. */
  29423. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29424. this._update(geometry);
  29425. return this;
  29426. };
  29427. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29428. if (updatable === void 0) { updatable = false; }
  29429. if (this.positions) {
  29430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29431. }
  29432. if (this.normals) {
  29433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29434. }
  29435. if (this.tangents) {
  29436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29437. }
  29438. if (this.uvs) {
  29439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29440. }
  29441. if (this.uvs2) {
  29442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29443. }
  29444. if (this.uvs3) {
  29445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29446. }
  29447. if (this.uvs4) {
  29448. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29449. }
  29450. if (this.uvs5) {
  29451. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29452. }
  29453. if (this.uvs6) {
  29454. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29455. }
  29456. if (this.colors) {
  29457. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29458. }
  29459. if (this.matricesIndices) {
  29460. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29461. }
  29462. if (this.matricesWeights) {
  29463. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29464. }
  29465. if (this.matricesIndicesExtra) {
  29466. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29467. }
  29468. if (this.matricesWeightsExtra) {
  29469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29470. }
  29471. if (this.indices) {
  29472. meshOrGeometry.setIndices(this.indices, null, updatable);
  29473. }
  29474. return this;
  29475. };
  29476. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29477. if (this.positions) {
  29478. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29479. }
  29480. if (this.normals) {
  29481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29482. }
  29483. if (this.tangents) {
  29484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29485. }
  29486. if (this.uvs) {
  29487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29488. }
  29489. if (this.uvs2) {
  29490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29491. }
  29492. if (this.uvs3) {
  29493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29494. }
  29495. if (this.uvs4) {
  29496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29497. }
  29498. if (this.uvs5) {
  29499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29500. }
  29501. if (this.uvs6) {
  29502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29503. }
  29504. if (this.colors) {
  29505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29506. }
  29507. if (this.matricesIndices) {
  29508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29509. }
  29510. if (this.matricesWeights) {
  29511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29512. }
  29513. if (this.matricesIndicesExtra) {
  29514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29515. }
  29516. if (this.matricesWeightsExtra) {
  29517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29518. }
  29519. if (this.indices) {
  29520. meshOrGeometry.setIndices(this.indices, null);
  29521. }
  29522. return this;
  29523. };
  29524. /**
  29525. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29526. * Returns the VertexData.
  29527. */
  29528. VertexData.prototype.transform = function (matrix) {
  29529. var transformed = BABYLON.Vector3.Zero();
  29530. var index;
  29531. if (this.positions) {
  29532. var position = BABYLON.Vector3.Zero();
  29533. for (index = 0; index < this.positions.length; index += 3) {
  29534. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29535. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29536. this.positions[index] = transformed.x;
  29537. this.positions[index + 1] = transformed.y;
  29538. this.positions[index + 2] = transformed.z;
  29539. }
  29540. }
  29541. if (this.normals) {
  29542. var normal = BABYLON.Vector3.Zero();
  29543. for (index = 0; index < this.normals.length; index += 3) {
  29544. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29545. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29546. this.normals[index] = transformed.x;
  29547. this.normals[index + 1] = transformed.y;
  29548. this.normals[index + 2] = transformed.z;
  29549. }
  29550. }
  29551. if (this.tangents) {
  29552. var tangent = BABYLON.Vector4.Zero();
  29553. var tangentTransformed = BABYLON.Vector4.Zero();
  29554. for (index = 0; index < this.tangents.length; index += 4) {
  29555. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29556. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29557. this.tangents[index] = tangentTransformed.x;
  29558. this.tangents[index + 1] = tangentTransformed.y;
  29559. this.tangents[index + 2] = tangentTransformed.z;
  29560. this.tangents[index + 3] = tangentTransformed.w;
  29561. }
  29562. }
  29563. return this;
  29564. };
  29565. /**
  29566. * Merges the passed VertexData into the current one.
  29567. * Returns the modified VertexData.
  29568. */
  29569. VertexData.prototype.merge = function (other, options) {
  29570. options = options || {};
  29571. if (other.indices) {
  29572. if (!this.indices) {
  29573. this.indices = [];
  29574. }
  29575. var offset = this.positions ? this.positions.length / 3 : 0;
  29576. for (var index = 0; index < other.indices.length; index++) {
  29577. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29578. this.indices.push(other.indices[index] + offset);
  29579. }
  29580. }
  29581. this.positions = this._mergeElement(this.positions, other.positions);
  29582. if (!this.positions) {
  29583. return this;
  29584. }
  29585. var count = this.positions.length / 3;
  29586. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29587. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29588. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29589. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29590. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29591. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29592. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29593. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29594. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29595. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29596. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29597. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29598. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29599. return this;
  29600. };
  29601. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29602. if (length === void 0) { length = 0; }
  29603. if (defaultValue === void 0) { defaultValue = 0; }
  29604. if (!other && !source) {
  29605. return null;
  29606. }
  29607. if (!other) {
  29608. var padding = new Float32Array(source.length);
  29609. padding.fill(defaultValue);
  29610. return this._mergeElement(source, padding, length);
  29611. }
  29612. if (!source) {
  29613. if (length === 0 || length === other.length) {
  29614. return other;
  29615. }
  29616. var padding = new Float32Array(length - other.length);
  29617. padding.fill(defaultValue);
  29618. return this._mergeElement(padding, other, length);
  29619. }
  29620. var len = other.length + source.length;
  29621. var isSrcTypedArray = source instanceof Float32Array;
  29622. var isOthTypedArray = other instanceof Float32Array;
  29623. // use non-loop method when the source is Float32Array
  29624. if (isSrcTypedArray) {
  29625. var ret32 = new Float32Array(len);
  29626. ret32.set(source);
  29627. ret32.set(other, source.length);
  29628. return ret32;
  29629. // source is number[], when other is also use concat
  29630. }
  29631. else if (!isOthTypedArray) {
  29632. return source.concat(other);
  29633. // source is a number[], but other is a Float32Array, loop required
  29634. }
  29635. else {
  29636. var ret = source.slice(0); // copy source to a separate array
  29637. for (var i = 0, len = other.length; i < len; i++) {
  29638. ret.push(other[i]);
  29639. }
  29640. return ret;
  29641. }
  29642. };
  29643. /**
  29644. * Serializes the VertexData.
  29645. * Returns a serialized object.
  29646. */
  29647. VertexData.prototype.serialize = function () {
  29648. var serializationObject = this.serialize();
  29649. if (this.positions) {
  29650. serializationObject.positions = this.positions;
  29651. }
  29652. if (this.normals) {
  29653. serializationObject.normals = this.normals;
  29654. }
  29655. if (this.tangents) {
  29656. serializationObject.tangents = this.tangents;
  29657. }
  29658. if (this.uvs) {
  29659. serializationObject.uvs = this.uvs;
  29660. }
  29661. if (this.uvs2) {
  29662. serializationObject.uvs2 = this.uvs2;
  29663. }
  29664. if (this.uvs3) {
  29665. serializationObject.uvs3 = this.uvs3;
  29666. }
  29667. if (this.uvs4) {
  29668. serializationObject.uvs4 = this.uvs4;
  29669. }
  29670. if (this.uvs5) {
  29671. serializationObject.uvs5 = this.uvs5;
  29672. }
  29673. if (this.uvs6) {
  29674. serializationObject.uvs6 = this.uvs6;
  29675. }
  29676. if (this.colors) {
  29677. serializationObject.colors = this.colors;
  29678. }
  29679. if (this.matricesIndices) {
  29680. serializationObject.matricesIndices = this.matricesIndices;
  29681. serializationObject.matricesIndices._isExpanded = true;
  29682. }
  29683. if (this.matricesWeights) {
  29684. serializationObject.matricesWeights = this.matricesWeights;
  29685. }
  29686. if (this.matricesIndicesExtra) {
  29687. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29688. serializationObject.matricesIndicesExtra._isExpanded = true;
  29689. }
  29690. if (this.matricesWeightsExtra) {
  29691. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29692. }
  29693. serializationObject.indices = this.indices;
  29694. return serializationObject;
  29695. };
  29696. // Statics
  29697. /**
  29698. * Returns the object VertexData associated to the passed mesh.
  29699. */
  29700. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29701. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29702. };
  29703. /**
  29704. * Returns the object VertexData associated to the passed geometry.
  29705. */
  29706. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29707. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29708. };
  29709. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29710. var result = new VertexData();
  29711. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29712. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29713. }
  29714. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29715. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29716. }
  29717. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29718. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29719. }
  29720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29721. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29722. }
  29723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29724. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29725. }
  29726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29727. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29728. }
  29729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29730. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29731. }
  29732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29733. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29734. }
  29735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29736. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29737. }
  29738. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29739. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29740. }
  29741. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29742. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29743. }
  29744. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29745. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29746. }
  29747. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29748. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29749. }
  29750. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29751. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29752. }
  29753. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29754. return result;
  29755. };
  29756. /**
  29757. * Creates the vertexData of the Ribbon.
  29758. */
  29759. VertexData.CreateRibbon = function (options) {
  29760. var pathArray = options.pathArray;
  29761. var closeArray = options.closeArray || false;
  29762. var closePath = options.closePath || false;
  29763. var invertUV = options.invertUV || false;
  29764. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29765. var offset = options.offset || defaultOffset;
  29766. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29767. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29768. var customUV = options.uvs;
  29769. var customColors = options.colors;
  29770. var positions = [];
  29771. var indices = [];
  29772. var normals = [];
  29773. var uvs = [];
  29774. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29775. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29776. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29777. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29778. var minlg; // minimal length among all paths from pathArray
  29779. var lg = []; // array of path lengths : nb of vertex per path
  29780. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29781. var p; // path iterator
  29782. var i; // point iterator
  29783. var j; // point iterator
  29784. // if single path in pathArray
  29785. if (pathArray.length < 2) {
  29786. var ar1 = [];
  29787. var ar2 = [];
  29788. for (i = 0; i < pathArray[0].length - offset; i++) {
  29789. ar1.push(pathArray[0][i]);
  29790. ar2.push(pathArray[0][i + offset]);
  29791. }
  29792. pathArray = [ar1, ar2];
  29793. }
  29794. // positions and horizontal distances (u)
  29795. var idc = 0;
  29796. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29797. var path;
  29798. var l;
  29799. minlg = pathArray[0].length;
  29800. var vectlg;
  29801. var dist;
  29802. for (p = 0; p < pathArray.length; p++) {
  29803. uTotalDistance[p] = 0;
  29804. us[p] = [0];
  29805. path = pathArray[p];
  29806. l = path.length;
  29807. minlg = (minlg < l) ? minlg : l;
  29808. j = 0;
  29809. while (j < l) {
  29810. positions.push(path[j].x, path[j].y, path[j].z);
  29811. if (j > 0) {
  29812. vectlg = path[j].subtract(path[j - 1]).length();
  29813. dist = vectlg + uTotalDistance[p];
  29814. us[p].push(dist);
  29815. uTotalDistance[p] = dist;
  29816. }
  29817. j++;
  29818. }
  29819. if (closePath) {
  29820. j--;
  29821. positions.push(path[0].x, path[0].y, path[0].z);
  29822. vectlg = path[j].subtract(path[0]).length();
  29823. dist = vectlg + uTotalDistance[p];
  29824. us[p].push(dist);
  29825. uTotalDistance[p] = dist;
  29826. }
  29827. lg[p] = l + closePathCorr;
  29828. idx[p] = idc;
  29829. idc += (l + closePathCorr);
  29830. }
  29831. // vertical distances (v)
  29832. var path1;
  29833. var path2;
  29834. var vertex1 = null;
  29835. var vertex2 = null;
  29836. for (i = 0; i < minlg + closePathCorr; i++) {
  29837. vTotalDistance[i] = 0;
  29838. vs[i] = [0];
  29839. for (p = 0; p < pathArray.length - 1; p++) {
  29840. path1 = pathArray[p];
  29841. path2 = pathArray[p + 1];
  29842. if (i === minlg) {
  29843. vertex1 = path1[0];
  29844. vertex2 = path2[0];
  29845. }
  29846. else {
  29847. vertex1 = path1[i];
  29848. vertex2 = path2[i];
  29849. }
  29850. vectlg = vertex2.subtract(vertex1).length();
  29851. dist = vectlg + vTotalDistance[i];
  29852. vs[i].push(dist);
  29853. vTotalDistance[i] = dist;
  29854. }
  29855. if (closeArray && vertex2 && vertex1) {
  29856. path1 = pathArray[p];
  29857. path2 = pathArray[0];
  29858. if (i === minlg) {
  29859. vertex2 = path2[0];
  29860. }
  29861. vectlg = vertex2.subtract(vertex1).length();
  29862. dist = vectlg + vTotalDistance[i];
  29863. vTotalDistance[i] = dist;
  29864. }
  29865. }
  29866. // uvs
  29867. var u;
  29868. var v;
  29869. if (customUV) {
  29870. for (p = 0; p < customUV.length; p++) {
  29871. uvs.push(customUV[p].x, customUV[p].y);
  29872. }
  29873. }
  29874. else {
  29875. for (p = 0; p < pathArray.length; p++) {
  29876. for (i = 0; i < minlg + closePathCorr; i++) {
  29877. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29878. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29879. if (invertUV) {
  29880. uvs.push(v, u);
  29881. }
  29882. else {
  29883. uvs.push(u, v);
  29884. }
  29885. }
  29886. }
  29887. }
  29888. // indices
  29889. p = 0; // path index
  29890. var pi = 0; // positions array index
  29891. var l1 = lg[p] - 1; // path1 length
  29892. var l2 = lg[p + 1] - 1; // path2 length
  29893. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29894. var shft = idx[1] - idx[0]; // shift
  29895. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29896. while (pi <= min && p < path1nb) {
  29897. // 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
  29898. indices.push(pi, pi + shft, pi + 1);
  29899. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29900. pi += 1;
  29901. if (pi === min) {
  29902. p++;
  29903. if (p === lg.length - 1) {
  29904. shft = idx[0] - idx[p];
  29905. l1 = lg[p] - 1;
  29906. l2 = lg[0] - 1;
  29907. }
  29908. else {
  29909. shft = idx[p + 1] - idx[p];
  29910. l1 = lg[p] - 1;
  29911. l2 = lg[p + 1] - 1;
  29912. }
  29913. pi = idx[p];
  29914. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29915. }
  29916. }
  29917. // normals
  29918. VertexData.ComputeNormals(positions, indices, normals);
  29919. if (closePath) {
  29920. var indexFirst = 0;
  29921. var indexLast = 0;
  29922. for (p = 0; p < pathArray.length; p++) {
  29923. indexFirst = idx[p] * 3;
  29924. if (p + 1 < pathArray.length) {
  29925. indexLast = (idx[p + 1] - 1) * 3;
  29926. }
  29927. else {
  29928. indexLast = normals.length - 3;
  29929. }
  29930. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29931. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29932. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29933. normals[indexLast] = normals[indexFirst];
  29934. normals[indexLast + 1] = normals[indexFirst + 1];
  29935. normals[indexLast + 2] = normals[indexFirst + 2];
  29936. }
  29937. }
  29938. // sides
  29939. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29940. // Colors
  29941. var colors = null;
  29942. if (customColors) {
  29943. colors = new Float32Array(customColors.length * 4);
  29944. for (var c = 0; c < customColors.length; c++) {
  29945. colors[c * 4] = customColors[c].r;
  29946. colors[c * 4 + 1] = customColors[c].g;
  29947. colors[c * 4 + 2] = customColors[c].b;
  29948. colors[c * 4 + 3] = customColors[c].a;
  29949. }
  29950. }
  29951. // Result
  29952. var vertexData = new VertexData();
  29953. var positions32 = new Float32Array(positions);
  29954. var normals32 = new Float32Array(normals);
  29955. var uvs32 = new Float32Array(uvs);
  29956. vertexData.indices = indices;
  29957. vertexData.positions = positions32;
  29958. vertexData.normals = normals32;
  29959. vertexData.uvs = uvs32;
  29960. if (colors) {
  29961. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29962. }
  29963. if (closePath) {
  29964. vertexData._idx = idx;
  29965. }
  29966. return vertexData;
  29967. };
  29968. /**
  29969. * Creates the VertexData of the Box.
  29970. */
  29971. VertexData.CreateBox = function (options) {
  29972. var normalsSource = [
  29973. new BABYLON.Vector3(0, 0, 1),
  29974. new BABYLON.Vector3(0, 0, -1),
  29975. new BABYLON.Vector3(1, 0, 0),
  29976. new BABYLON.Vector3(-1, 0, 0),
  29977. new BABYLON.Vector3(0, 1, 0),
  29978. new BABYLON.Vector3(0, -1, 0)
  29979. ];
  29980. var indices = [];
  29981. var positions = [];
  29982. var normals = [];
  29983. var uvs = [];
  29984. var width = options.width || options.size || 1;
  29985. var height = options.height || options.size || 1;
  29986. var depth = options.depth || options.size || 1;
  29987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29988. var faceUV = options.faceUV || new Array(6);
  29989. var faceColors = options.faceColors;
  29990. var colors = [];
  29991. // default face colors and UV if undefined
  29992. for (var f = 0; f < 6; f++) {
  29993. if (faceUV[f] === undefined) {
  29994. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29995. }
  29996. if (faceColors && faceColors[f] === undefined) {
  29997. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29998. }
  29999. }
  30000. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30001. // Create each face in turn.
  30002. for (var index = 0; index < normalsSource.length; index++) {
  30003. var normal = normalsSource[index];
  30004. // Get two vectors perpendicular to the face normal and to each other.
  30005. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30006. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30007. // Six indices (two triangles) per face.
  30008. var verticesLength = positions.length / 3;
  30009. indices.push(verticesLength);
  30010. indices.push(verticesLength + 1);
  30011. indices.push(verticesLength + 2);
  30012. indices.push(verticesLength);
  30013. indices.push(verticesLength + 2);
  30014. indices.push(verticesLength + 3);
  30015. // Four vertices per face.
  30016. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30017. positions.push(vertex.x, vertex.y, vertex.z);
  30018. normals.push(normal.x, normal.y, normal.z);
  30019. uvs.push(faceUV[index].z, faceUV[index].w);
  30020. if (faceColors) {
  30021. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30022. }
  30023. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30024. positions.push(vertex.x, vertex.y, vertex.z);
  30025. normals.push(normal.x, normal.y, normal.z);
  30026. uvs.push(faceUV[index].x, faceUV[index].w);
  30027. if (faceColors) {
  30028. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30029. }
  30030. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30031. positions.push(vertex.x, vertex.y, vertex.z);
  30032. normals.push(normal.x, normal.y, normal.z);
  30033. uvs.push(faceUV[index].x, faceUV[index].y);
  30034. if (faceColors) {
  30035. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30036. }
  30037. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30038. positions.push(vertex.x, vertex.y, vertex.z);
  30039. normals.push(normal.x, normal.y, normal.z);
  30040. uvs.push(faceUV[index].z, faceUV[index].y);
  30041. if (faceColors) {
  30042. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30043. }
  30044. }
  30045. // sides
  30046. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30047. // Result
  30048. var vertexData = new VertexData();
  30049. vertexData.indices = indices;
  30050. vertexData.positions = positions;
  30051. vertexData.normals = normals;
  30052. vertexData.uvs = uvs;
  30053. if (faceColors) {
  30054. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30055. vertexData.colors = totalColors;
  30056. }
  30057. return vertexData;
  30058. };
  30059. /**
  30060. * Creates the VertexData of the Sphere.
  30061. */
  30062. VertexData.CreateSphere = function (options) {
  30063. var segments = options.segments || 32;
  30064. var diameterX = options.diameterX || options.diameter || 1;
  30065. var diameterY = options.diameterY || options.diameter || 1;
  30066. var diameterZ = options.diameterZ || options.diameter || 1;
  30067. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30068. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30070. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30071. var totalZRotationSteps = 2 + segments;
  30072. var totalYRotationSteps = 2 * totalZRotationSteps;
  30073. var indices = [];
  30074. var positions = [];
  30075. var normals = [];
  30076. var uvs = [];
  30077. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30078. var normalizedZ = zRotationStep / totalZRotationSteps;
  30079. var angleZ = normalizedZ * Math.PI * slice;
  30080. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30081. var normalizedY = yRotationStep / totalYRotationSteps;
  30082. var angleY = normalizedY * Math.PI * 2 * arc;
  30083. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30084. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30085. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30086. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30087. var vertex = complete.multiply(radius);
  30088. var normal = complete.divide(radius).normalize();
  30089. positions.push(vertex.x, vertex.y, vertex.z);
  30090. normals.push(normal.x, normal.y, normal.z);
  30091. uvs.push(normalizedY, normalizedZ);
  30092. }
  30093. if (zRotationStep > 0) {
  30094. var verticesCount = positions.length / 3;
  30095. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30096. indices.push((firstIndex));
  30097. indices.push((firstIndex + 1));
  30098. indices.push(firstIndex + totalYRotationSteps + 1);
  30099. indices.push((firstIndex + totalYRotationSteps + 1));
  30100. indices.push((firstIndex + 1));
  30101. indices.push((firstIndex + totalYRotationSteps + 2));
  30102. }
  30103. }
  30104. }
  30105. // Sides
  30106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30107. // Result
  30108. var vertexData = new VertexData();
  30109. vertexData.indices = indices;
  30110. vertexData.positions = positions;
  30111. vertexData.normals = normals;
  30112. vertexData.uvs = uvs;
  30113. return vertexData;
  30114. };
  30115. /**
  30116. * Creates the VertexData of the Cylinder or Cone.
  30117. */
  30118. VertexData.CreateCylinder = function (options) {
  30119. var height = options.height || 2;
  30120. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30121. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30122. var tessellation = options.tessellation || 24;
  30123. var subdivisions = options.subdivisions || 1;
  30124. var hasRings = options.hasRings ? true : false;
  30125. var enclose = options.enclose ? true : false;
  30126. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30128. var faceUV = options.faceUV || new Array(3);
  30129. var faceColors = options.faceColors;
  30130. // default face colors and UV if undefined
  30131. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30132. var ringNb = (hasRings) ? subdivisions : 1;
  30133. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30134. var f;
  30135. for (f = 0; f < surfaceNb; f++) {
  30136. if (faceColors && faceColors[f] === undefined) {
  30137. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30138. }
  30139. }
  30140. for (f = 0; f < surfaceNb; f++) {
  30141. if (faceUV && faceUV[f] === undefined) {
  30142. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30143. }
  30144. }
  30145. var indices = new Array();
  30146. var positions = new Array();
  30147. var normals = new Array();
  30148. var uvs = new Array();
  30149. var colors = new Array();
  30150. var angle_step = Math.PI * 2 * arc / tessellation;
  30151. var angle;
  30152. var h;
  30153. var radius;
  30154. var tan = (diameterBottom - diameterTop) / 2 / height;
  30155. var ringVertex = BABYLON.Vector3.Zero();
  30156. var ringNormal = BABYLON.Vector3.Zero();
  30157. var ringFirstVertex = BABYLON.Vector3.Zero();
  30158. var ringFirstNormal = BABYLON.Vector3.Zero();
  30159. var quadNormal = BABYLON.Vector3.Zero();
  30160. var Y = BABYLON.Axis.Y;
  30161. // positions, normals, uvs
  30162. var i;
  30163. var j;
  30164. var r;
  30165. var ringIdx = 1;
  30166. var s = 1; // surface index
  30167. var cs = 0;
  30168. var v = 0;
  30169. for (i = 0; i <= subdivisions; i++) {
  30170. h = i / subdivisions;
  30171. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30172. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30173. for (r = 0; r < ringIdx; r++) {
  30174. if (hasRings) {
  30175. s += r;
  30176. }
  30177. if (enclose) {
  30178. s += 2 * r;
  30179. }
  30180. for (j = 0; j <= tessellation; j++) {
  30181. angle = j * angle_step;
  30182. // position
  30183. ringVertex.x = Math.cos(-angle) * radius;
  30184. ringVertex.y = -height / 2 + h * height;
  30185. ringVertex.z = Math.sin(-angle) * radius;
  30186. // normal
  30187. if (diameterTop === 0 && i === subdivisions) {
  30188. // if no top cap, reuse former normals
  30189. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30190. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30191. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30192. }
  30193. else {
  30194. ringNormal.x = ringVertex.x;
  30195. ringNormal.z = ringVertex.z;
  30196. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30197. ringNormal.normalize();
  30198. }
  30199. // keep first ring vertex values for enclose
  30200. if (j === 0) {
  30201. ringFirstVertex.copyFrom(ringVertex);
  30202. ringFirstNormal.copyFrom(ringNormal);
  30203. }
  30204. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30205. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30206. if (hasRings) {
  30207. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30208. }
  30209. else {
  30210. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30211. }
  30212. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30213. if (faceColors) {
  30214. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30215. }
  30216. }
  30217. // if enclose, add four vertices and their dedicated normals
  30218. if (arc !== 1 && enclose) {
  30219. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30220. positions.push(0, ringVertex.y, 0);
  30221. positions.push(0, ringVertex.y, 0);
  30222. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30223. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30224. quadNormal.normalize();
  30225. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30226. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30227. quadNormal.normalize();
  30228. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30229. if (hasRings) {
  30230. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30231. }
  30232. else {
  30233. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30234. }
  30235. uvs.push(faceUV[s + 1].x, v);
  30236. uvs.push(faceUV[s + 1].z, v);
  30237. if (hasRings) {
  30238. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30239. }
  30240. else {
  30241. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30242. }
  30243. uvs.push(faceUV[s + 2].x, v);
  30244. uvs.push(faceUV[s + 2].z, v);
  30245. if (faceColors) {
  30246. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30247. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30248. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30249. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30250. }
  30251. }
  30252. if (cs !== s) {
  30253. cs = s;
  30254. }
  30255. }
  30256. }
  30257. // indices
  30258. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30259. var s;
  30260. i = 0;
  30261. for (s = 0; s < subdivisions; s++) {
  30262. var i0 = 0;
  30263. var i1 = 0;
  30264. var i2 = 0;
  30265. var i3 = 0;
  30266. for (j = 0; j < tessellation; j++) {
  30267. i0 = i * (e + 1) + j;
  30268. i1 = (i + 1) * (e + 1) + j;
  30269. i2 = i * (e + 1) + (j + 1);
  30270. i3 = (i + 1) * (e + 1) + (j + 1);
  30271. indices.push(i0, i1, i2);
  30272. indices.push(i3, i2, i1);
  30273. }
  30274. if (arc !== 1 && enclose) {
  30275. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30276. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30277. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30278. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30279. }
  30280. i = (hasRings) ? (i + 2) : (i + 1);
  30281. }
  30282. // Caps
  30283. var createCylinderCap = function (isTop) {
  30284. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30285. if (radius === 0) {
  30286. return;
  30287. }
  30288. // Cap positions, normals & uvs
  30289. var angle;
  30290. var circleVector;
  30291. var i;
  30292. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30293. var c = null;
  30294. if (faceColors) {
  30295. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30296. }
  30297. // cap center
  30298. var vbase = positions.length / 3;
  30299. var offset = isTop ? height / 2 : -height / 2;
  30300. var center = new BABYLON.Vector3(0, offset, 0);
  30301. positions.push(center.x, center.y, center.z);
  30302. normals.push(0, isTop ? 1 : -1, 0);
  30303. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30304. if (c) {
  30305. colors.push(c.r, c.g, c.b, c.a);
  30306. }
  30307. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30308. for (i = 0; i <= tessellation; i++) {
  30309. angle = Math.PI * 2 * i * arc / tessellation;
  30310. var cos = Math.cos(-angle);
  30311. var sin = Math.sin(-angle);
  30312. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30313. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30314. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30315. normals.push(0, isTop ? 1 : -1, 0);
  30316. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30317. if (c) {
  30318. colors.push(c.r, c.g, c.b, c.a);
  30319. }
  30320. }
  30321. // Cap indices
  30322. for (i = 0; i < tessellation; i++) {
  30323. if (!isTop) {
  30324. indices.push(vbase);
  30325. indices.push(vbase + (i + 1));
  30326. indices.push(vbase + (i + 2));
  30327. }
  30328. else {
  30329. indices.push(vbase);
  30330. indices.push(vbase + (i + 2));
  30331. indices.push(vbase + (i + 1));
  30332. }
  30333. }
  30334. };
  30335. // add caps to geometry
  30336. createCylinderCap(false);
  30337. createCylinderCap(true);
  30338. // Sides
  30339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30340. var vertexData = new VertexData();
  30341. vertexData.indices = indices;
  30342. vertexData.positions = positions;
  30343. vertexData.normals = normals;
  30344. vertexData.uvs = uvs;
  30345. if (faceColors) {
  30346. vertexData.colors = colors;
  30347. }
  30348. return vertexData;
  30349. };
  30350. /**
  30351. * Creates the VertexData of the Torus.
  30352. */
  30353. VertexData.CreateTorus = function (options) {
  30354. var indices = [];
  30355. var positions = [];
  30356. var normals = [];
  30357. var uvs = [];
  30358. var diameter = options.diameter || 1;
  30359. var thickness = options.thickness || 0.5;
  30360. var tessellation = options.tessellation || 16;
  30361. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30362. var stride = tessellation + 1;
  30363. for (var i = 0; i <= tessellation; i++) {
  30364. var u = i / tessellation;
  30365. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30366. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30367. for (var j = 0; j <= tessellation; j++) {
  30368. var v = 1 - j / tessellation;
  30369. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30370. var dx = Math.cos(innerAngle);
  30371. var dy = Math.sin(innerAngle);
  30372. // Create a vertex.
  30373. var normal = new BABYLON.Vector3(dx, dy, 0);
  30374. var position = normal.scale(thickness / 2);
  30375. var textureCoordinate = new BABYLON.Vector2(u, v);
  30376. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30377. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30378. positions.push(position.x, position.y, position.z);
  30379. normals.push(normal.x, normal.y, normal.z);
  30380. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30381. // And create indices for two triangles.
  30382. var nextI = (i + 1) % stride;
  30383. var nextJ = (j + 1) % stride;
  30384. indices.push(i * stride + j);
  30385. indices.push(i * stride + nextJ);
  30386. indices.push(nextI * stride + j);
  30387. indices.push(i * stride + nextJ);
  30388. indices.push(nextI * stride + nextJ);
  30389. indices.push(nextI * stride + j);
  30390. }
  30391. }
  30392. // Sides
  30393. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30394. // Result
  30395. var vertexData = new VertexData();
  30396. vertexData.indices = indices;
  30397. vertexData.positions = positions;
  30398. vertexData.normals = normals;
  30399. vertexData.uvs = uvs;
  30400. return vertexData;
  30401. };
  30402. /**
  30403. * Creates the VertexData of the LineSystem.
  30404. */
  30405. VertexData.CreateLineSystem = function (options) {
  30406. var indices = [];
  30407. var positions = [];
  30408. var lines = options.lines;
  30409. var colors = options.colors;
  30410. var vertexColors = [];
  30411. var idx = 0;
  30412. for (var l = 0; l < lines.length; l++) {
  30413. var points = lines[l];
  30414. for (var index = 0; index < points.length; index++) {
  30415. positions.push(points[index].x, points[index].y, points[index].z);
  30416. if (colors) {
  30417. var color = colors[l];
  30418. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30419. }
  30420. if (index > 0) {
  30421. indices.push(idx - 1);
  30422. indices.push(idx);
  30423. }
  30424. idx++;
  30425. }
  30426. }
  30427. var vertexData = new VertexData();
  30428. vertexData.indices = indices;
  30429. vertexData.positions = positions;
  30430. if (colors) {
  30431. vertexData.colors = vertexColors;
  30432. }
  30433. return vertexData;
  30434. };
  30435. /**
  30436. * Create the VertexData of the DashedLines.
  30437. */
  30438. VertexData.CreateDashedLines = function (options) {
  30439. var dashSize = options.dashSize || 3;
  30440. var gapSize = options.gapSize || 1;
  30441. var dashNb = options.dashNb || 200;
  30442. var points = options.points;
  30443. var positions = new Array();
  30444. var indices = new Array();
  30445. var curvect = BABYLON.Vector3.Zero();
  30446. var lg = 0;
  30447. var nb = 0;
  30448. var shft = 0;
  30449. var dashshft = 0;
  30450. var curshft = 0;
  30451. var idx = 0;
  30452. var i = 0;
  30453. for (i = 0; i < points.length - 1; i++) {
  30454. points[i + 1].subtractToRef(points[i], curvect);
  30455. lg += curvect.length();
  30456. }
  30457. shft = lg / dashNb;
  30458. dashshft = dashSize * shft / (dashSize + gapSize);
  30459. for (i = 0; i < points.length - 1; i++) {
  30460. points[i + 1].subtractToRef(points[i], curvect);
  30461. nb = Math.floor(curvect.length() / shft);
  30462. curvect.normalize();
  30463. for (var j = 0; j < nb; j++) {
  30464. curshft = shft * j;
  30465. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30466. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30467. indices.push(idx, idx + 1);
  30468. idx += 2;
  30469. }
  30470. }
  30471. // Result
  30472. var vertexData = new VertexData();
  30473. vertexData.positions = positions;
  30474. vertexData.indices = indices;
  30475. return vertexData;
  30476. };
  30477. /**
  30478. * Creates the VertexData of the Ground.
  30479. */
  30480. VertexData.CreateGround = function (options) {
  30481. var indices = [];
  30482. var positions = [];
  30483. var normals = [];
  30484. var uvs = [];
  30485. var row, col;
  30486. var width = options.width || 1;
  30487. var height = options.height || 1;
  30488. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30489. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30490. for (row = 0; row <= subdivisionsY; row++) {
  30491. for (col = 0; col <= subdivisionsX; col++) {
  30492. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30493. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30494. positions.push(position.x, position.y, position.z);
  30495. normals.push(normal.x, normal.y, normal.z);
  30496. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30497. }
  30498. }
  30499. for (row = 0; row < subdivisionsY; row++) {
  30500. for (col = 0; col < subdivisionsX; col++) {
  30501. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30502. indices.push(col + 1 + row * (subdivisionsX + 1));
  30503. indices.push(col + row * (subdivisionsX + 1));
  30504. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30505. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30506. indices.push(col + row * (subdivisionsX + 1));
  30507. }
  30508. }
  30509. // Result
  30510. var vertexData = new VertexData();
  30511. vertexData.indices = indices;
  30512. vertexData.positions = positions;
  30513. vertexData.normals = normals;
  30514. vertexData.uvs = uvs;
  30515. return vertexData;
  30516. };
  30517. /**
  30518. * Creates the VertexData of the TiledGround.
  30519. */
  30520. VertexData.CreateTiledGround = function (options) {
  30521. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30522. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30523. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30524. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30525. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30526. var precision = options.precision || { w: 1, h: 1 };
  30527. var indices = new Array();
  30528. var positions = new Array();
  30529. var normals = new Array();
  30530. var uvs = new Array();
  30531. var row, col, tileRow, tileCol;
  30532. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30533. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30534. precision.w = (precision.w < 1) ? 1 : precision.w;
  30535. precision.h = (precision.h < 1) ? 1 : precision.h;
  30536. var tileSize = {
  30537. 'w': (xmax - xmin) / subdivisions.w,
  30538. 'h': (zmax - zmin) / subdivisions.h
  30539. };
  30540. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30541. // Indices
  30542. var base = positions.length / 3;
  30543. var rowLength = precision.w + 1;
  30544. for (row = 0; row < precision.h; row++) {
  30545. for (col = 0; col < precision.w; col++) {
  30546. var square = [
  30547. base + col + row * rowLength,
  30548. base + (col + 1) + row * rowLength,
  30549. base + (col + 1) + (row + 1) * rowLength,
  30550. base + col + (row + 1) * rowLength
  30551. ];
  30552. indices.push(square[1]);
  30553. indices.push(square[2]);
  30554. indices.push(square[3]);
  30555. indices.push(square[0]);
  30556. indices.push(square[1]);
  30557. indices.push(square[3]);
  30558. }
  30559. }
  30560. // Position, normals and uvs
  30561. var position = BABYLON.Vector3.Zero();
  30562. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30563. for (row = 0; row <= precision.h; row++) {
  30564. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30565. for (col = 0; col <= precision.w; col++) {
  30566. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30567. position.y = 0;
  30568. positions.push(position.x, position.y, position.z);
  30569. normals.push(normal.x, normal.y, normal.z);
  30570. uvs.push(col / precision.w, row / precision.h);
  30571. }
  30572. }
  30573. }
  30574. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30575. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30576. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30577. }
  30578. }
  30579. // Result
  30580. var vertexData = new VertexData();
  30581. vertexData.indices = indices;
  30582. vertexData.positions = positions;
  30583. vertexData.normals = normals;
  30584. vertexData.uvs = uvs;
  30585. return vertexData;
  30586. };
  30587. /**
  30588. * Creates the VertexData of the Ground designed from a heightmap.
  30589. */
  30590. VertexData.CreateGroundFromHeightMap = function (options) {
  30591. var indices = [];
  30592. var positions = [];
  30593. var normals = [];
  30594. var uvs = [];
  30595. var row, col;
  30596. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30597. // Vertices
  30598. for (row = 0; row <= options.subdivisions; row++) {
  30599. for (col = 0; col <= options.subdivisions; col++) {
  30600. 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));
  30601. // Compute height
  30602. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30603. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30604. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30605. var r = options.buffer[pos] / 255.0;
  30606. var g = options.buffer[pos + 1] / 255.0;
  30607. var b = options.buffer[pos + 2] / 255.0;
  30608. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30609. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30610. // Add vertex
  30611. positions.push(position.x, position.y, position.z);
  30612. normals.push(0, 0, 0);
  30613. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30614. }
  30615. }
  30616. // Indices
  30617. for (row = 0; row < options.subdivisions; row++) {
  30618. for (col = 0; col < options.subdivisions; col++) {
  30619. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30620. indices.push(col + 1 + row * (options.subdivisions + 1));
  30621. indices.push(col + row * (options.subdivisions + 1));
  30622. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30623. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30624. indices.push(col + row * (options.subdivisions + 1));
  30625. }
  30626. }
  30627. // Normals
  30628. VertexData.ComputeNormals(positions, indices, normals);
  30629. // Result
  30630. var vertexData = new VertexData();
  30631. vertexData.indices = indices;
  30632. vertexData.positions = positions;
  30633. vertexData.normals = normals;
  30634. vertexData.uvs = uvs;
  30635. return vertexData;
  30636. };
  30637. /**
  30638. * Creates the VertexData of the Plane.
  30639. */
  30640. VertexData.CreatePlane = function (options) {
  30641. var indices = [];
  30642. var positions = [];
  30643. var normals = [];
  30644. var uvs = [];
  30645. var width = options.width || options.size || 1;
  30646. var height = options.height || options.size || 1;
  30647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30648. // Vertices
  30649. var halfWidth = width / 2.0;
  30650. var halfHeight = height / 2.0;
  30651. positions.push(-halfWidth, -halfHeight, 0);
  30652. normals.push(0, 0, -1.0);
  30653. uvs.push(0.0, 0.0);
  30654. positions.push(halfWidth, -halfHeight, 0);
  30655. normals.push(0, 0, -1.0);
  30656. uvs.push(1.0, 0.0);
  30657. positions.push(halfWidth, halfHeight, 0);
  30658. normals.push(0, 0, -1.0);
  30659. uvs.push(1.0, 1.0);
  30660. positions.push(-halfWidth, halfHeight, 0);
  30661. normals.push(0, 0, -1.0);
  30662. uvs.push(0.0, 1.0);
  30663. // Indices
  30664. indices.push(0);
  30665. indices.push(1);
  30666. indices.push(2);
  30667. indices.push(0);
  30668. indices.push(2);
  30669. indices.push(3);
  30670. // Sides
  30671. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30672. // Result
  30673. var vertexData = new VertexData();
  30674. vertexData.indices = indices;
  30675. vertexData.positions = positions;
  30676. vertexData.normals = normals;
  30677. vertexData.uvs = uvs;
  30678. return vertexData;
  30679. };
  30680. /**
  30681. * Creates the VertexData of the Disc or regular Polygon.
  30682. */
  30683. VertexData.CreateDisc = function (options) {
  30684. var positions = new Array();
  30685. var indices = new Array();
  30686. var normals = new Array();
  30687. var uvs = new Array();
  30688. var radius = options.radius || 0.5;
  30689. var tessellation = options.tessellation || 64;
  30690. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30692. // positions and uvs
  30693. positions.push(0, 0, 0); // disc center first
  30694. uvs.push(0.5, 0.5);
  30695. var theta = Math.PI * 2 * arc;
  30696. var step = theta / tessellation;
  30697. for (var a = 0; a < theta; a += step) {
  30698. var x = Math.cos(a);
  30699. var y = Math.sin(a);
  30700. var u = (x + 1) / 2;
  30701. var v = (1 - y) / 2;
  30702. positions.push(radius * x, radius * y, 0);
  30703. uvs.push(u, v);
  30704. }
  30705. if (arc === 1) {
  30706. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30707. uvs.push(uvs[2], uvs[3]);
  30708. }
  30709. //indices
  30710. var vertexNb = positions.length / 3;
  30711. for (var i = 1; i < vertexNb - 1; i++) {
  30712. indices.push(i + 1, 0, i);
  30713. }
  30714. // result
  30715. VertexData.ComputeNormals(positions, indices, normals);
  30716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30717. var vertexData = new VertexData();
  30718. vertexData.indices = indices;
  30719. vertexData.positions = positions;
  30720. vertexData.normals = normals;
  30721. vertexData.uvs = uvs;
  30722. return vertexData;
  30723. };
  30724. /**
  30725. * Re-creates the VertexData of the Polygon for sideOrientation.
  30726. */
  30727. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30728. var faceUV = fUV || new Array(3);
  30729. var faceColors = fColors;
  30730. var colors = [];
  30731. // default face colors and UV if undefined
  30732. for (var f = 0; f < 3; f++) {
  30733. if (faceUV[f] === undefined) {
  30734. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30735. }
  30736. if (faceColors && faceColors[f] === undefined) {
  30737. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30738. }
  30739. }
  30740. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30741. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30742. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30743. var indices = polygon.getIndices();
  30744. // set face colours and textures
  30745. var idx = 0;
  30746. var face = 0;
  30747. for (var index = 0; index < normals.length; index += 3) {
  30748. //Edge Face no. 1
  30749. if (Math.abs(normals[index + 1]) < 0.001) {
  30750. face = 1;
  30751. }
  30752. //Top Face no. 0
  30753. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30754. face = 0;
  30755. }
  30756. //Bottom Face no. 2
  30757. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30758. face = 2;
  30759. }
  30760. idx = index / 3;
  30761. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30762. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30763. if (faceColors) {
  30764. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30765. }
  30766. }
  30767. // sides
  30768. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30769. // Result
  30770. var vertexData = new VertexData();
  30771. vertexData.indices = indices;
  30772. vertexData.positions = positions;
  30773. vertexData.normals = normals;
  30774. vertexData.uvs = uvs;
  30775. if (faceColors) {
  30776. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30777. vertexData.colors = totalColors;
  30778. }
  30779. return vertexData;
  30780. };
  30781. /**
  30782. * Creates the VertexData of the IcoSphere.
  30783. */
  30784. VertexData.CreateIcoSphere = function (options) {
  30785. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30786. var radius = options.radius || 1;
  30787. var flat = (options.flat === undefined) ? true : options.flat;
  30788. var subdivisions = options.subdivisions || 4;
  30789. var radiusX = options.radiusX || radius;
  30790. var radiusY = options.radiusY || radius;
  30791. var radiusZ = options.radiusZ || radius;
  30792. var t = (1 + Math.sqrt(5)) / 2;
  30793. // 12 vertex x,y,z
  30794. var ico_vertices = [
  30795. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30796. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30797. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30798. ];
  30799. // index of 3 vertex makes a face of icopshere
  30800. var ico_indices = [
  30801. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30802. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30803. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30804. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30805. ];
  30806. // vertex for uv have aliased position, not for UV
  30807. var vertices_unalias_id = [
  30808. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30809. // vertex alias
  30810. 0,
  30811. 2,
  30812. 3,
  30813. 3,
  30814. 3,
  30815. 4,
  30816. 7,
  30817. 8,
  30818. 9,
  30819. 9,
  30820. 10,
  30821. 11 // 23: B + 12
  30822. ];
  30823. // uv as integer step (not pixels !)
  30824. var ico_vertexuv = [
  30825. 5, 1, 3, 1, 6, 4, 0, 0,
  30826. 5, 3, 4, 2, 2, 2, 4, 0,
  30827. 2, 0, 1, 1, 6, 0, 6, 2,
  30828. // vertex alias (for same vertex on different faces)
  30829. 0, 4,
  30830. 3, 3,
  30831. 4, 4,
  30832. 3, 1,
  30833. 4, 2,
  30834. 4, 4,
  30835. 0, 2,
  30836. 1, 1,
  30837. 2, 2,
  30838. 3, 3,
  30839. 1, 3,
  30840. 2, 4 // 23: B + 12
  30841. ];
  30842. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30843. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30844. // First island of uv mapping
  30845. // v = 4h 3+ 2
  30846. // v = 3h 9+ 4
  30847. // v = 2h 9+ 5 B
  30848. // v = 1h 9 1 0
  30849. // v = 0h 3 8 7 A
  30850. // u = 0 1 2 3 4 5 6 *a
  30851. // Second island of uv mapping
  30852. // v = 4h 0+ B+ 4+
  30853. // v = 3h A+ 2+
  30854. // v = 2h 7+ 6 3+
  30855. // v = 1h 8+ 3+
  30856. // v = 0h
  30857. // u = 0 1 2 3 4 5 6 *a
  30858. // Face layout on texture UV mapping
  30859. // ============
  30860. // \ 4 /\ 16 / ======
  30861. // \ / \ / /\ 11 /
  30862. // \/ 7 \/ / \ /
  30863. // ======= / 10 \/
  30864. // /\ 17 /\ =======
  30865. // / \ / \ \ 15 /\
  30866. // / 8 \/ 12 \ \ / \
  30867. // ============ \/ 6 \
  30868. // \ 18 /\ ============
  30869. // \ / \ \ 5 /\ 0 /
  30870. // \/ 13 \ \ / \ /
  30871. // ======= \/ 1 \/
  30872. // =============
  30873. // /\ 19 /\ 2 /\
  30874. // / \ / \ / \
  30875. // / 14 \/ 9 \/ 3 \
  30876. // ===================
  30877. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30878. var ustep = 138 / 1024;
  30879. var vstep = 239 / 1024;
  30880. var uoffset = 60 / 1024;
  30881. var voffset = 26 / 1024;
  30882. // Second island should have margin, not to touch the first island
  30883. // avoid any borderline artefact in pixel rounding
  30884. var island_u_offset = -40 / 1024;
  30885. var island_v_offset = +20 / 1024;
  30886. // face is either island 0 or 1 :
  30887. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30888. var island = [
  30889. 0, 0, 0, 0, 1,
  30890. 0, 0, 1, 1, 0,
  30891. 0, 0, 1, 1, 0,
  30892. 0, 1, 1, 1, 0 // 15 - 19
  30893. ];
  30894. var indices = new Array();
  30895. var positions = new Array();
  30896. var normals = new Array();
  30897. var uvs = new Array();
  30898. var current_indice = 0;
  30899. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30900. var face_vertex_pos = new Array(3);
  30901. var face_vertex_uv = new Array(3);
  30902. var v012;
  30903. for (v012 = 0; v012 < 3; v012++) {
  30904. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30905. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30906. }
  30907. // create all with normals
  30908. for (var face = 0; face < 20; face++) {
  30909. // 3 vertex per face
  30910. for (v012 = 0; v012 < 3; v012++) {
  30911. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30912. var v_id = ico_indices[3 * face + v012];
  30913. // vertex have 3D position (x,y,z)
  30914. 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]);
  30915. // Normalize to get normal, then scale to radius
  30916. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30917. // uv Coordinates from vertex ID
  30918. 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);
  30919. }
  30920. // Subdivide the face (interpolate pos, norm, uv)
  30921. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30922. // - norm is linear interpolation of vertex corner normal
  30923. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30924. // - uv is linear interpolation
  30925. //
  30926. // Topology is as below for sub-divide by 2
  30927. // vertex shown as v0,v1,v2
  30928. // interp index is i1 to progress in range [v0,v1[
  30929. // interp index is i2 to progress in range [v0,v2[
  30930. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30931. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30932. //
  30933. //
  30934. // i2 v2
  30935. // ^ ^
  30936. // / / \
  30937. // / / \
  30938. // / / \
  30939. // / / (0,1) \
  30940. // / #---------\
  30941. // / / \ (0,0)'/ \
  30942. // / / \ / \
  30943. // / / \ / \
  30944. // / / (0,0) \ / (1,0) \
  30945. // / #---------#---------\
  30946. // v0 v1
  30947. //
  30948. // --------------------> i1
  30949. //
  30950. // interp of (i1,i2):
  30951. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30952. // along i1 : lerp(x0,x1, i1/(S-i2))
  30953. //
  30954. // centroid of triangle is needed to get help normal computation
  30955. // (c1,c2) are used for centroid location
  30956. var interp_vertex = function (i1, i2, c1, c2) {
  30957. // vertex is interpolated from
  30958. // - face_vertex_pos[0..2]
  30959. // - face_vertex_uv[0..2]
  30960. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30961. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30962. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30963. pos_interp.normalize();
  30964. var vertex_normal;
  30965. if (flat) {
  30966. // in flat mode, recalculate normal as face centroid normal
  30967. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30968. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30969. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30970. }
  30971. else {
  30972. // in smooth mode, recalculate normal from each single vertex position
  30973. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30974. }
  30975. // Vertex normal need correction due to X,Y,Z radius scaling
  30976. vertex_normal.x /= radiusX;
  30977. vertex_normal.y /= radiusY;
  30978. vertex_normal.z /= radiusZ;
  30979. vertex_normal.normalize();
  30980. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30981. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30982. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30983. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30984. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30985. uvs.push(uv_interp.x, uv_interp.y);
  30986. // push each vertex has member of a face
  30987. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30988. indices.push(current_indice);
  30989. current_indice++;
  30990. };
  30991. for (var i2 = 0; i2 < subdivisions; i2++) {
  30992. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30993. // face : (i1,i2) for /\ :
  30994. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30995. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30996. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30997. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30998. if (i1 + i2 + 1 < subdivisions) {
  30999. // face : (i1,i2)' for \/ :
  31000. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31001. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31002. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31003. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31004. }
  31005. }
  31006. }
  31007. }
  31008. // Sides
  31009. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31010. // Result
  31011. var vertexData = new VertexData();
  31012. vertexData.indices = indices;
  31013. vertexData.positions = positions;
  31014. vertexData.normals = normals;
  31015. vertexData.uvs = uvs;
  31016. return vertexData;
  31017. };
  31018. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31019. /**
  31020. * Creates the VertexData of the Polyhedron.
  31021. */
  31022. VertexData.CreatePolyhedron = function (options) {
  31023. // provided polyhedron types :
  31024. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31025. // 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)
  31026. var polyhedra = [];
  31027. 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]] };
  31028. 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]] };
  31029. polyhedra[2] = {
  31030. 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]],
  31031. 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]]
  31032. };
  31033. polyhedra[3] = {
  31034. 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]],
  31035. 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]]
  31036. };
  31037. polyhedra[4] = {
  31038. 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]],
  31039. 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]]
  31040. };
  31041. 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]] };
  31042. 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]] };
  31043. 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]] };
  31044. 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]] };
  31045. 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]] };
  31046. 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]] };
  31047. 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]] };
  31048. 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]] };
  31049. 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]] };
  31050. polyhedra[14] = {
  31051. 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]],
  31052. 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]]
  31053. };
  31054. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31055. var size = options.size;
  31056. var sizeX = options.sizeX || size || 1;
  31057. var sizeY = options.sizeY || size || 1;
  31058. var sizeZ = options.sizeZ || size || 1;
  31059. var data = options.custom || polyhedra[type];
  31060. var nbfaces = data.face.length;
  31061. var faceUV = options.faceUV || new Array(nbfaces);
  31062. var faceColors = options.faceColors;
  31063. var flat = (options.flat === undefined) ? true : options.flat;
  31064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31065. var positions = new Array();
  31066. var indices = new Array();
  31067. var normals = new Array();
  31068. var uvs = new Array();
  31069. var colors = new Array();
  31070. var index = 0;
  31071. var faceIdx = 0; // face cursor in the array "indexes"
  31072. var indexes = new Array();
  31073. var i = 0;
  31074. var f = 0;
  31075. var u, v, ang, x, y, tmp;
  31076. // default face colors and UV if undefined
  31077. if (flat) {
  31078. for (f = 0; f < nbfaces; f++) {
  31079. if (faceColors && faceColors[f] === undefined) {
  31080. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31081. }
  31082. if (faceUV && faceUV[f] === undefined) {
  31083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31084. }
  31085. }
  31086. }
  31087. if (!flat) {
  31088. for (i = 0; i < data.vertex.length; i++) {
  31089. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31090. uvs.push(0, 0);
  31091. }
  31092. for (f = 0; f < nbfaces; f++) {
  31093. for (i = 0; i < data.face[f].length - 2; i++) {
  31094. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31095. }
  31096. }
  31097. }
  31098. else {
  31099. for (f = 0; f < nbfaces; f++) {
  31100. var fl = data.face[f].length; // number of vertices of the current face
  31101. ang = 2 * Math.PI / fl;
  31102. x = 0.5 * Math.tan(ang / 2);
  31103. y = 0.5;
  31104. // positions, uvs, colors
  31105. for (i = 0; i < fl; i++) {
  31106. // positions
  31107. 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);
  31108. indexes.push(index);
  31109. index++;
  31110. // uvs
  31111. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31112. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31113. uvs.push(u, v);
  31114. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31115. y = x * Math.sin(ang) + y * Math.cos(ang);
  31116. x = tmp;
  31117. // colors
  31118. if (faceColors) {
  31119. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31120. }
  31121. }
  31122. // indices from indexes
  31123. for (i = 0; i < fl - 2; i++) {
  31124. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31125. }
  31126. faceIdx += fl;
  31127. }
  31128. }
  31129. VertexData.ComputeNormals(positions, indices, normals);
  31130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31131. var vertexData = new VertexData();
  31132. vertexData.positions = positions;
  31133. vertexData.indices = indices;
  31134. vertexData.normals = normals;
  31135. vertexData.uvs = uvs;
  31136. if (faceColors && flat) {
  31137. vertexData.colors = colors;
  31138. }
  31139. return vertexData;
  31140. };
  31141. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31142. /**
  31143. * Creates the VertexData of the Torus Knot.
  31144. */
  31145. VertexData.CreateTorusKnot = function (options) {
  31146. var indices = new Array();
  31147. var positions = new Array();
  31148. var normals = new Array();
  31149. var uvs = new Array();
  31150. var radius = options.radius || 2;
  31151. var tube = options.tube || 0.5;
  31152. var radialSegments = options.radialSegments || 32;
  31153. var tubularSegments = options.tubularSegments || 32;
  31154. var p = options.p || 2;
  31155. var q = options.q || 3;
  31156. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31157. // Helper
  31158. var getPos = function (angle) {
  31159. var cu = Math.cos(angle);
  31160. var su = Math.sin(angle);
  31161. var quOverP = q / p * angle;
  31162. var cs = Math.cos(quOverP);
  31163. var tx = radius * (2 + cs) * 0.5 * cu;
  31164. var ty = radius * (2 + cs) * su * 0.5;
  31165. var tz = radius * Math.sin(quOverP) * 0.5;
  31166. return new BABYLON.Vector3(tx, ty, tz);
  31167. };
  31168. // Vertices
  31169. var i;
  31170. var j;
  31171. for (i = 0; i <= radialSegments; i++) {
  31172. var modI = i % radialSegments;
  31173. var u = modI / radialSegments * 2 * p * Math.PI;
  31174. var p1 = getPos(u);
  31175. var p2 = getPos(u + 0.01);
  31176. var tang = p2.subtract(p1);
  31177. var n = p2.add(p1);
  31178. var bitan = BABYLON.Vector3.Cross(tang, n);
  31179. n = BABYLON.Vector3.Cross(bitan, tang);
  31180. bitan.normalize();
  31181. n.normalize();
  31182. for (j = 0; j < tubularSegments; j++) {
  31183. var modJ = j % tubularSegments;
  31184. var v = modJ / tubularSegments * 2 * Math.PI;
  31185. var cx = -tube * Math.cos(v);
  31186. var cy = tube * Math.sin(v);
  31187. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31188. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31189. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31190. uvs.push(i / radialSegments);
  31191. uvs.push(j / tubularSegments);
  31192. }
  31193. }
  31194. for (i = 0; i < radialSegments; i++) {
  31195. for (j = 0; j < tubularSegments; j++) {
  31196. var jNext = (j + 1) % tubularSegments;
  31197. var a = i * tubularSegments + j;
  31198. var b = (i + 1) * tubularSegments + j;
  31199. var c = (i + 1) * tubularSegments + jNext;
  31200. var d = i * tubularSegments + jNext;
  31201. indices.push(d);
  31202. indices.push(b);
  31203. indices.push(a);
  31204. indices.push(d);
  31205. indices.push(c);
  31206. indices.push(b);
  31207. }
  31208. }
  31209. // Normals
  31210. VertexData.ComputeNormals(positions, indices, normals);
  31211. // Sides
  31212. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31213. // Result
  31214. var vertexData = new VertexData();
  31215. vertexData.indices = indices;
  31216. vertexData.positions = positions;
  31217. vertexData.normals = normals;
  31218. vertexData.uvs = uvs;
  31219. return vertexData;
  31220. };
  31221. // Tools
  31222. /**
  31223. * @param {any} - positions (number[] or Float32Array)
  31224. * @param {any} - indices (number[] or Uint16Array)
  31225. * @param {any} - normals (number[] or Float32Array)
  31226. * options (optional) :
  31227. * facetPositions : optional array of facet positions (vector3)
  31228. * facetNormals : optional array of facet normals (vector3)
  31229. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31230. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31231. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31232. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31233. * bInfo : optional bounding info, required for facetPartitioning computation
  31234. * useRightHandedSystem: optional boolean to for right handed system computation
  31235. * depthSort : optional boolean to enable the facet depth sort computation
  31236. * distanceTo : optional Vector3 to compute the facet depth from this location
  31237. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31238. */
  31239. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31240. // temporary scalar variables
  31241. var index = 0; // facet index
  31242. var p1p2x = 0.0; // p1p2 vector x coordinate
  31243. var p1p2y = 0.0; // p1p2 vector y coordinate
  31244. var p1p2z = 0.0; // p1p2 vector z coordinate
  31245. var p3p2x = 0.0; // p3p2 vector x coordinate
  31246. var p3p2y = 0.0; // p3p2 vector y coordinate
  31247. var p3p2z = 0.0; // p3p2 vector z coordinate
  31248. var faceNormalx = 0.0; // facet normal x coordinate
  31249. var faceNormaly = 0.0; // facet normal y coordinate
  31250. var faceNormalz = 0.0; // facet normal z coordinate
  31251. var length = 0.0; // facet normal length before normalization
  31252. var v1x = 0; // vector1 x index in the positions array
  31253. var v1y = 0; // vector1 y index in the positions array
  31254. var v1z = 0; // vector1 z index in the positions array
  31255. var v2x = 0; // vector2 x index in the positions array
  31256. var v2y = 0; // vector2 y index in the positions array
  31257. var v2z = 0; // vector2 z index in the positions array
  31258. var v3x = 0; // vector3 x index in the positions array
  31259. var v3y = 0; // vector3 y index in the positions array
  31260. var v3z = 0; // vector3 z index in the positions array
  31261. var computeFacetNormals = false;
  31262. var computeFacetPositions = false;
  31263. var computeFacetPartitioning = false;
  31264. var computeDepthSort = false;
  31265. var faceNormalSign = 1;
  31266. var ratio = 0;
  31267. var distanceTo = null;
  31268. if (options) {
  31269. computeFacetNormals = (options.facetNormals) ? true : false;
  31270. computeFacetPositions = (options.facetPositions) ? true : false;
  31271. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31272. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31273. ratio = options.ratio || 0;
  31274. computeDepthSort = (options.depthSort) ? true : false;
  31275. distanceTo = (options.distanceTo);
  31276. if (computeDepthSort) {
  31277. if (distanceTo === undefined) {
  31278. distanceTo = BABYLON.Vector3.Zero();
  31279. }
  31280. var depthSortedFacets = options.depthSortedFacets;
  31281. }
  31282. }
  31283. // facetPartitioning reinit if needed
  31284. var xSubRatio = 0;
  31285. var ySubRatio = 0;
  31286. var zSubRatio = 0;
  31287. var subSq = 0;
  31288. if (computeFacetPartitioning && options && options.bbSize) {
  31289. var ox = 0; // X partitioning index for facet position
  31290. var oy = 0; // Y partinioning index for facet position
  31291. var oz = 0; // Z partinioning index for facet position
  31292. var b1x = 0; // X partitioning index for facet v1 vertex
  31293. var b1y = 0; // Y partitioning index for facet v1 vertex
  31294. var b1z = 0; // z partitioning index for facet v1 vertex
  31295. var b2x = 0; // X partitioning index for facet v2 vertex
  31296. var b2y = 0; // Y partitioning index for facet v2 vertex
  31297. var b2z = 0; // Z partitioning index for facet v2 vertex
  31298. var b3x = 0; // X partitioning index for facet v3 vertex
  31299. var b3y = 0; // Y partitioning index for facet v3 vertex
  31300. var b3z = 0; // Z partitioning index for facet v3 vertex
  31301. var block_idx_o = 0; // facet barycenter block index
  31302. var block_idx_v1 = 0; // v1 vertex block index
  31303. var block_idx_v2 = 0; // v2 vertex block index
  31304. var block_idx_v3 = 0; // v3 vertex block index
  31305. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31306. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31307. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31308. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31309. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31310. subSq = options.subDiv.max * options.subDiv.max;
  31311. options.facetPartitioning.length = 0;
  31312. }
  31313. // reset the normals
  31314. for (index = 0; index < positions.length; index++) {
  31315. normals[index] = 0.0;
  31316. }
  31317. // Loop : 1 indice triplet = 1 facet
  31318. var nbFaces = (indices.length / 3) | 0;
  31319. for (index = 0; index < nbFaces; index++) {
  31320. // get the indexes of the coordinates of each vertex of the facet
  31321. v1x = indices[index * 3] * 3;
  31322. v1y = v1x + 1;
  31323. v1z = v1x + 2;
  31324. v2x = indices[index * 3 + 1] * 3;
  31325. v2y = v2x + 1;
  31326. v2z = v2x + 2;
  31327. v3x = indices[index * 3 + 2] * 3;
  31328. v3y = v3x + 1;
  31329. v3z = v3x + 2;
  31330. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31331. p1p2y = positions[v1y] - positions[v2y];
  31332. p1p2z = positions[v1z] - positions[v2z];
  31333. p3p2x = positions[v3x] - positions[v2x];
  31334. p3p2y = positions[v3y] - positions[v2y];
  31335. p3p2z = positions[v3z] - positions[v2z];
  31336. // compute the face normal with the cross product
  31337. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31338. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31339. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31340. // normalize this normal and store it in the array facetData
  31341. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31342. length = (length === 0) ? 1.0 : length;
  31343. faceNormalx /= length;
  31344. faceNormaly /= length;
  31345. faceNormalz /= length;
  31346. if (computeFacetNormals && options) {
  31347. options.facetNormals[index].x = faceNormalx;
  31348. options.facetNormals[index].y = faceNormaly;
  31349. options.facetNormals[index].z = faceNormalz;
  31350. }
  31351. if (computeFacetPositions && options) {
  31352. // compute and the facet barycenter coordinates in the array facetPositions
  31353. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31354. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31355. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31356. }
  31357. if (computeFacetPartitioning && options) {
  31358. // store the facet indexes in arrays in the main facetPartitioning array :
  31359. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31360. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31361. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31362. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31363. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31364. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31365. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31366. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31367. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31368. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31369. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31370. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31371. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31372. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31373. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31374. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31375. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31376. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31377. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31378. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31379. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31380. // push each facet index in each block containing the vertex
  31381. options.facetPartitioning[block_idx_v1].push(index);
  31382. if (block_idx_v2 != block_idx_v1) {
  31383. options.facetPartitioning[block_idx_v2].push(index);
  31384. }
  31385. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31386. options.facetPartitioning[block_idx_v3].push(index);
  31387. }
  31388. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31389. options.facetPartitioning[block_idx_o].push(index);
  31390. }
  31391. }
  31392. if (computeDepthSort && options && options.facetPositions) {
  31393. var dsf = depthSortedFacets[index];
  31394. dsf.ind = index * 3;
  31395. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31396. }
  31397. // compute the normals anyway
  31398. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31399. normals[v1y] += faceNormaly;
  31400. normals[v1z] += faceNormalz;
  31401. normals[v2x] += faceNormalx;
  31402. normals[v2y] += faceNormaly;
  31403. normals[v2z] += faceNormalz;
  31404. normals[v3x] += faceNormalx;
  31405. normals[v3y] += faceNormaly;
  31406. normals[v3z] += faceNormalz;
  31407. }
  31408. // last normalization of each normal
  31409. for (index = 0; index < normals.length / 3; index++) {
  31410. faceNormalx = normals[index * 3];
  31411. faceNormaly = normals[index * 3 + 1];
  31412. faceNormalz = normals[index * 3 + 2];
  31413. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31414. length = (length === 0) ? 1.0 : length;
  31415. faceNormalx /= length;
  31416. faceNormaly /= length;
  31417. faceNormalz /= length;
  31418. normals[index * 3] = faceNormalx;
  31419. normals[index * 3 + 1] = faceNormaly;
  31420. normals[index * 3 + 2] = faceNormalz;
  31421. }
  31422. };
  31423. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31424. var li = indices.length;
  31425. var ln = normals.length;
  31426. var i;
  31427. var n;
  31428. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31429. switch (sideOrientation) {
  31430. case BABYLON.Mesh.FRONTSIDE:
  31431. // nothing changed
  31432. break;
  31433. case BABYLON.Mesh.BACKSIDE:
  31434. var tmp;
  31435. // indices
  31436. for (i = 0; i < li; i += 3) {
  31437. tmp = indices[i];
  31438. indices[i] = indices[i + 2];
  31439. indices[i + 2] = tmp;
  31440. }
  31441. // normals
  31442. for (n = 0; n < ln; n++) {
  31443. normals[n] = -normals[n];
  31444. }
  31445. break;
  31446. case BABYLON.Mesh.DOUBLESIDE:
  31447. // positions
  31448. var lp = positions.length;
  31449. var l = lp / 3;
  31450. for (var p = 0; p < lp; p++) {
  31451. positions[lp + p] = positions[p];
  31452. }
  31453. // indices
  31454. for (i = 0; i < li; i += 3) {
  31455. indices[i + li] = indices[i + 2] + l;
  31456. indices[i + 1 + li] = indices[i + 1] + l;
  31457. indices[i + 2 + li] = indices[i] + l;
  31458. }
  31459. // normals
  31460. for (n = 0; n < ln; n++) {
  31461. normals[ln + n] = -normals[n];
  31462. }
  31463. // uvs
  31464. var lu = uvs.length;
  31465. var u = 0;
  31466. for (u = 0; u < lu; u++) {
  31467. uvs[u + lu] = uvs[u];
  31468. }
  31469. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31470. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31471. u = 0;
  31472. for (i = 0; i < lu / 2; i++) {
  31473. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31474. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31475. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31476. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31477. u += 2;
  31478. }
  31479. break;
  31480. }
  31481. };
  31482. /**
  31483. * Creates a new VertexData from the imported parameters.
  31484. */
  31485. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31486. var vertexData = new VertexData();
  31487. // positions
  31488. var positions = parsedVertexData.positions;
  31489. if (positions) {
  31490. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31491. }
  31492. // normals
  31493. var normals = parsedVertexData.normals;
  31494. if (normals) {
  31495. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31496. }
  31497. // tangents
  31498. var tangents = parsedVertexData.tangents;
  31499. if (tangents) {
  31500. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31501. }
  31502. // uvs
  31503. var uvs = parsedVertexData.uvs;
  31504. if (uvs) {
  31505. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31506. }
  31507. // uv2s
  31508. var uv2s = parsedVertexData.uv2s;
  31509. if (uv2s) {
  31510. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31511. }
  31512. // uv3s
  31513. var uv3s = parsedVertexData.uv3s;
  31514. if (uv3s) {
  31515. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31516. }
  31517. // uv4s
  31518. var uv4s = parsedVertexData.uv4s;
  31519. if (uv4s) {
  31520. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31521. }
  31522. // uv5s
  31523. var uv5s = parsedVertexData.uv5s;
  31524. if (uv5s) {
  31525. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31526. }
  31527. // uv6s
  31528. var uv6s = parsedVertexData.uv6s;
  31529. if (uv6s) {
  31530. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31531. }
  31532. // colors
  31533. var colors = parsedVertexData.colors;
  31534. if (colors) {
  31535. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31536. }
  31537. // matricesIndices
  31538. var matricesIndices = parsedVertexData.matricesIndices;
  31539. if (matricesIndices) {
  31540. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31541. }
  31542. // matricesWeights
  31543. var matricesWeights = parsedVertexData.matricesWeights;
  31544. if (matricesWeights) {
  31545. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31546. }
  31547. // indices
  31548. var indices = parsedVertexData.indices;
  31549. if (indices) {
  31550. vertexData.indices = indices;
  31551. }
  31552. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31553. };
  31554. return VertexData;
  31555. }());
  31556. BABYLON.VertexData = VertexData;
  31557. })(BABYLON || (BABYLON = {}));
  31558. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31559. var BABYLON;
  31560. (function (BABYLON) {
  31561. var Geometry = /** @class */ (function () {
  31562. function Geometry(id, scene, vertexData, updatable, mesh) {
  31563. if (updatable === void 0) { updatable = false; }
  31564. if (mesh === void 0) { mesh = null; }
  31565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31566. this._totalVertices = 0;
  31567. this._isDisposed = false;
  31568. this._indexBufferIsUpdatable = false;
  31569. this.id = id;
  31570. this._engine = scene.getEngine();
  31571. this._meshes = [];
  31572. this._scene = scene;
  31573. //Init vertex buffer cache
  31574. this._vertexBuffers = {};
  31575. this._indices = [];
  31576. this._updatable = updatable;
  31577. // vertexData
  31578. if (vertexData) {
  31579. this.setAllVerticesData(vertexData, updatable);
  31580. }
  31581. else {
  31582. this._totalVertices = 0;
  31583. this._indices = [];
  31584. }
  31585. if (this._engine.getCaps().vertexArrayObject) {
  31586. this._vertexArrayObjects = {};
  31587. }
  31588. // applyToMesh
  31589. if (mesh) {
  31590. if (mesh.getClassName() === "LinesMesh") {
  31591. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31592. this.updateExtend();
  31593. }
  31594. this.applyToMesh(mesh);
  31595. mesh.computeWorldMatrix(true);
  31596. }
  31597. }
  31598. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31599. /**
  31600. * 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
  31601. * @returns The Bias Vector
  31602. */
  31603. get: function () {
  31604. return this._boundingBias;
  31605. },
  31606. set: function (value) {
  31607. if (this._boundingBias && this._boundingBias.equals(value)) {
  31608. return;
  31609. }
  31610. this._boundingBias = value.clone();
  31611. this.updateBoundingInfo(true, null);
  31612. },
  31613. enumerable: true,
  31614. configurable: true
  31615. });
  31616. Geometry.CreateGeometryForMesh = function (mesh) {
  31617. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31618. geometry.applyToMesh(mesh);
  31619. return geometry;
  31620. };
  31621. Object.defineProperty(Geometry.prototype, "extend", {
  31622. get: function () {
  31623. return this._extend;
  31624. },
  31625. enumerable: true,
  31626. configurable: true
  31627. });
  31628. Geometry.prototype.getScene = function () {
  31629. return this._scene;
  31630. };
  31631. Geometry.prototype.getEngine = function () {
  31632. return this._engine;
  31633. };
  31634. Geometry.prototype.isReady = function () {
  31635. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31636. };
  31637. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31638. get: function () {
  31639. for (var index = 0; index < this._meshes.length; index++) {
  31640. if (!this._meshes[index].doNotSerialize) {
  31641. return false;
  31642. }
  31643. }
  31644. return true;
  31645. },
  31646. enumerable: true,
  31647. configurable: true
  31648. });
  31649. Geometry.prototype._rebuild = function () {
  31650. if (this._vertexArrayObjects) {
  31651. this._vertexArrayObjects = {};
  31652. }
  31653. // Index buffer
  31654. if (this._meshes.length !== 0 && this._indices) {
  31655. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31656. }
  31657. // Vertex buffers
  31658. for (var key in this._vertexBuffers) {
  31659. var vertexBuffer = this._vertexBuffers[key];
  31660. vertexBuffer._rebuild();
  31661. }
  31662. };
  31663. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31664. vertexData.applyToGeometry(this, updatable);
  31665. this.notifyUpdate();
  31666. };
  31667. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31668. if (updatable === void 0) { updatable = false; }
  31669. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31670. this.setVerticesBuffer(buffer);
  31671. };
  31672. Geometry.prototype.removeVerticesData = function (kind) {
  31673. if (this._vertexBuffers[kind]) {
  31674. this._vertexBuffers[kind].dispose();
  31675. delete this._vertexBuffers[kind];
  31676. }
  31677. };
  31678. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31679. var kind = buffer.getKind();
  31680. if (this._vertexBuffers[kind]) {
  31681. this._vertexBuffers[kind].dispose();
  31682. }
  31683. this._vertexBuffers[kind] = buffer;
  31684. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31685. var data = buffer.getData();
  31686. var stride = buffer.getStrideSize();
  31687. this._totalVertices = data.length / stride;
  31688. this.updateExtend(data, stride);
  31689. this._resetPointsArrayCache();
  31690. var meshes = this._meshes;
  31691. var numOfMeshes = meshes.length;
  31692. for (var index = 0; index < numOfMeshes; index++) {
  31693. var mesh = meshes[index];
  31694. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31695. mesh._createGlobalSubMesh(false);
  31696. mesh.computeWorldMatrix(true);
  31697. }
  31698. }
  31699. this.notifyUpdate(kind);
  31700. if (this._vertexArrayObjects) {
  31701. this._disposeVertexArrayObjects();
  31702. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31703. }
  31704. };
  31705. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31706. var vertexBuffer = this.getVertexBuffer(kind);
  31707. if (!vertexBuffer) {
  31708. return;
  31709. }
  31710. vertexBuffer.updateDirectly(data, offset);
  31711. this.notifyUpdate(kind);
  31712. };
  31713. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31714. if (updateExtends === void 0) { updateExtends = false; }
  31715. var vertexBuffer = this.getVertexBuffer(kind);
  31716. if (!vertexBuffer) {
  31717. return;
  31718. }
  31719. vertexBuffer.update(data);
  31720. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31721. var stride = vertexBuffer.getStrideSize();
  31722. this._totalVertices = data.length / stride;
  31723. this.updateBoundingInfo(updateExtends, data);
  31724. }
  31725. this.notifyUpdate(kind);
  31726. };
  31727. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31728. if (updateExtends) {
  31729. this.updateExtend(data);
  31730. }
  31731. var meshes = this._meshes;
  31732. var numOfMeshes = meshes.length;
  31733. this._resetPointsArrayCache();
  31734. for (var index = 0; index < numOfMeshes; index++) {
  31735. var mesh = meshes[index];
  31736. if (updateExtends) {
  31737. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31738. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31739. var subMesh = mesh.subMeshes[subIndex];
  31740. subMesh.refreshBoundingInfo();
  31741. }
  31742. }
  31743. }
  31744. };
  31745. Geometry.prototype._bind = function (effect, indexToBind) {
  31746. if (!effect) {
  31747. return;
  31748. }
  31749. if (indexToBind === undefined) {
  31750. indexToBind = this._indexBuffer;
  31751. }
  31752. var vbs = this.getVertexBuffers();
  31753. if (!vbs) {
  31754. return;
  31755. }
  31756. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31757. this._engine.bindBuffers(vbs, indexToBind, effect);
  31758. return;
  31759. }
  31760. // Using VAO
  31761. if (!this._vertexArrayObjects[effect.key]) {
  31762. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31763. }
  31764. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31765. };
  31766. Geometry.prototype.getTotalVertices = function () {
  31767. if (!this.isReady()) {
  31768. return 0;
  31769. }
  31770. return this._totalVertices;
  31771. };
  31772. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31773. var vertexBuffer = this.getVertexBuffer(kind);
  31774. if (!vertexBuffer) {
  31775. return null;
  31776. }
  31777. var orig = vertexBuffer.getData();
  31778. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31779. return orig;
  31780. }
  31781. else {
  31782. var len = orig.length;
  31783. var copy = [];
  31784. for (var i = 0; i < len; i++) {
  31785. copy.push(orig[i]);
  31786. }
  31787. return copy;
  31788. }
  31789. };
  31790. /**
  31791. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31792. * Possible `kind` values :
  31793. * - BABYLON.VertexBuffer.PositionKind
  31794. * - BABYLON.VertexBuffer.UVKind
  31795. * - BABYLON.VertexBuffer.UV2Kind
  31796. * - BABYLON.VertexBuffer.UV3Kind
  31797. * - BABYLON.VertexBuffer.UV4Kind
  31798. * - BABYLON.VertexBuffer.UV5Kind
  31799. * - BABYLON.VertexBuffer.UV6Kind
  31800. * - BABYLON.VertexBuffer.ColorKind
  31801. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31802. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31803. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31804. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31805. */
  31806. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31807. var vb = this._vertexBuffers[kind];
  31808. if (!vb) {
  31809. return false;
  31810. }
  31811. return vb.isUpdatable();
  31812. };
  31813. Geometry.prototype.getVertexBuffer = function (kind) {
  31814. if (!this.isReady()) {
  31815. return null;
  31816. }
  31817. return this._vertexBuffers[kind];
  31818. };
  31819. Geometry.prototype.getVertexBuffers = function () {
  31820. if (!this.isReady()) {
  31821. return null;
  31822. }
  31823. return this._vertexBuffers;
  31824. };
  31825. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31826. if (!this._vertexBuffers) {
  31827. if (this._delayInfo) {
  31828. return this._delayInfo.indexOf(kind) !== -1;
  31829. }
  31830. return false;
  31831. }
  31832. return this._vertexBuffers[kind] !== undefined;
  31833. };
  31834. Geometry.prototype.getVerticesDataKinds = function () {
  31835. var result = [];
  31836. var kind;
  31837. if (!this._vertexBuffers && this._delayInfo) {
  31838. for (kind in this._delayInfo) {
  31839. result.push(kind);
  31840. }
  31841. }
  31842. else {
  31843. for (kind in this._vertexBuffers) {
  31844. result.push(kind);
  31845. }
  31846. }
  31847. return result;
  31848. };
  31849. Geometry.prototype.updateIndices = function (indices, offset) {
  31850. if (!this._indexBuffer) {
  31851. return;
  31852. }
  31853. if (!this._indexBufferIsUpdatable) {
  31854. this.setIndices(indices, null, true);
  31855. }
  31856. else {
  31857. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31858. }
  31859. };
  31860. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31861. if (totalVertices === void 0) { totalVertices = null; }
  31862. if (updatable === void 0) { updatable = false; }
  31863. if (this._indexBuffer) {
  31864. this._engine._releaseBuffer(this._indexBuffer);
  31865. }
  31866. this._disposeVertexArrayObjects();
  31867. this._indices = indices;
  31868. this._indexBufferIsUpdatable = updatable;
  31869. if (this._meshes.length !== 0 && this._indices) {
  31870. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31871. }
  31872. if (totalVertices != undefined) {
  31873. this._totalVertices = totalVertices;
  31874. }
  31875. var meshes = this._meshes;
  31876. var numOfMeshes = meshes.length;
  31877. for (var index = 0; index < numOfMeshes; index++) {
  31878. meshes[index]._createGlobalSubMesh(true);
  31879. }
  31880. this.notifyUpdate();
  31881. };
  31882. Geometry.prototype.getTotalIndices = function () {
  31883. if (!this.isReady()) {
  31884. return 0;
  31885. }
  31886. return this._indices.length;
  31887. };
  31888. Geometry.prototype.getIndices = function (copyWhenShared) {
  31889. if (!this.isReady()) {
  31890. return null;
  31891. }
  31892. var orig = this._indices;
  31893. if (!copyWhenShared || this._meshes.length === 1) {
  31894. return orig;
  31895. }
  31896. else {
  31897. var len = orig.length;
  31898. var copy = [];
  31899. for (var i = 0; i < len; i++) {
  31900. copy.push(orig[i]);
  31901. }
  31902. return copy;
  31903. }
  31904. };
  31905. Geometry.prototype.getIndexBuffer = function () {
  31906. if (!this.isReady()) {
  31907. return null;
  31908. }
  31909. return this._indexBuffer;
  31910. };
  31911. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31912. if (effect === void 0) { effect = null; }
  31913. if (!effect || !this._vertexArrayObjects) {
  31914. return;
  31915. }
  31916. if (this._vertexArrayObjects[effect.key]) {
  31917. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31918. delete this._vertexArrayObjects[effect.key];
  31919. }
  31920. };
  31921. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31922. var meshes = this._meshes;
  31923. var index = meshes.indexOf(mesh);
  31924. if (index === -1) {
  31925. return;
  31926. }
  31927. meshes.splice(index, 1);
  31928. mesh._geometry = null;
  31929. if (meshes.length === 0 && shouldDispose) {
  31930. this.dispose();
  31931. }
  31932. };
  31933. Geometry.prototype.applyToMesh = function (mesh) {
  31934. if (mesh._geometry === this) {
  31935. return;
  31936. }
  31937. var previousGeometry = mesh._geometry;
  31938. if (previousGeometry) {
  31939. previousGeometry.releaseForMesh(mesh);
  31940. }
  31941. var meshes = this._meshes;
  31942. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31943. mesh._geometry = this;
  31944. this._scene.pushGeometry(this);
  31945. meshes.push(mesh);
  31946. if (this.isReady()) {
  31947. this._applyToMesh(mesh);
  31948. }
  31949. else {
  31950. mesh._boundingInfo = this._boundingInfo;
  31951. }
  31952. };
  31953. Geometry.prototype.updateExtend = function (data, stride) {
  31954. if (data === void 0) { data = null; }
  31955. if (!data) {
  31956. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31957. }
  31958. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31959. };
  31960. Geometry.prototype._applyToMesh = function (mesh) {
  31961. var numOfMeshes = this._meshes.length;
  31962. // vertexBuffers
  31963. for (var kind in this._vertexBuffers) {
  31964. if (numOfMeshes === 1) {
  31965. this._vertexBuffers[kind].create();
  31966. }
  31967. var buffer = this._vertexBuffers[kind].getBuffer();
  31968. if (buffer)
  31969. buffer.references = numOfMeshes;
  31970. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31971. if (!this._extend) {
  31972. this.updateExtend(this._vertexBuffers[kind].getData());
  31973. }
  31974. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31975. mesh._createGlobalSubMesh(false);
  31976. //bounding info was just created again, world matrix should be applied again.
  31977. mesh._updateBoundingInfo();
  31978. }
  31979. }
  31980. // indexBuffer
  31981. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31982. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31983. }
  31984. if (this._indexBuffer) {
  31985. this._indexBuffer.references = numOfMeshes;
  31986. }
  31987. };
  31988. Geometry.prototype.notifyUpdate = function (kind) {
  31989. if (this.onGeometryUpdated) {
  31990. this.onGeometryUpdated(this, kind);
  31991. }
  31992. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31993. var mesh = _a[_i];
  31994. mesh._markSubMeshesAsAttributesDirty();
  31995. }
  31996. };
  31997. Geometry.prototype.load = function (scene, onLoaded) {
  31998. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31999. return;
  32000. }
  32001. if (this.isReady()) {
  32002. if (onLoaded) {
  32003. onLoaded();
  32004. }
  32005. return;
  32006. }
  32007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32008. this._queueLoad(scene, onLoaded);
  32009. };
  32010. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32011. var _this = this;
  32012. if (!this.delayLoadingFile) {
  32013. return;
  32014. }
  32015. scene._addPendingData(this);
  32016. scene._loadFile(this.delayLoadingFile, function (data) {
  32017. if (!_this._delayLoadingFunction) {
  32018. return;
  32019. }
  32020. _this._delayLoadingFunction(JSON.parse(data), _this);
  32021. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32022. _this._delayInfo = [];
  32023. scene._removePendingData(_this);
  32024. var meshes = _this._meshes;
  32025. var numOfMeshes = meshes.length;
  32026. for (var index = 0; index < numOfMeshes; index++) {
  32027. _this._applyToMesh(meshes[index]);
  32028. }
  32029. if (onLoaded) {
  32030. onLoaded();
  32031. }
  32032. }, undefined, true);
  32033. };
  32034. /**
  32035. * Invert the geometry to move from a right handed system to a left handed one.
  32036. */
  32037. Geometry.prototype.toLeftHanded = function () {
  32038. // Flip faces
  32039. var tIndices = this.getIndices(false);
  32040. if (tIndices != null && tIndices.length > 0) {
  32041. for (var i = 0; i < tIndices.length; i += 3) {
  32042. var tTemp = tIndices[i + 0];
  32043. tIndices[i + 0] = tIndices[i + 2];
  32044. tIndices[i + 2] = tTemp;
  32045. }
  32046. this.setIndices(tIndices);
  32047. }
  32048. // Negate position.z
  32049. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32050. if (tPositions != null && tPositions.length > 0) {
  32051. for (var i = 0; i < tPositions.length; i += 3) {
  32052. tPositions[i + 2] = -tPositions[i + 2];
  32053. }
  32054. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32055. }
  32056. // Negate normal.z
  32057. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32058. if (tNormals != null && tNormals.length > 0) {
  32059. for (var i = 0; i < tNormals.length; i += 3) {
  32060. tNormals[i + 2] = -tNormals[i + 2];
  32061. }
  32062. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32063. }
  32064. };
  32065. // Cache
  32066. Geometry.prototype._resetPointsArrayCache = function () {
  32067. this._positions = null;
  32068. };
  32069. Geometry.prototype._generatePointsArray = function () {
  32070. if (this._positions)
  32071. return true;
  32072. this._positions = [];
  32073. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32074. if (!data) {
  32075. return false;
  32076. }
  32077. for (var index = 0; index < data.length; index += 3) {
  32078. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32079. }
  32080. return true;
  32081. };
  32082. Geometry.prototype.isDisposed = function () {
  32083. return this._isDisposed;
  32084. };
  32085. Geometry.prototype._disposeVertexArrayObjects = function () {
  32086. if (this._vertexArrayObjects) {
  32087. for (var kind in this._vertexArrayObjects) {
  32088. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32089. }
  32090. this._vertexArrayObjects = {};
  32091. }
  32092. };
  32093. Geometry.prototype.dispose = function () {
  32094. var meshes = this._meshes;
  32095. var numOfMeshes = meshes.length;
  32096. var index;
  32097. for (index = 0; index < numOfMeshes; index++) {
  32098. this.releaseForMesh(meshes[index]);
  32099. }
  32100. this._meshes = [];
  32101. this._disposeVertexArrayObjects();
  32102. for (var kind in this._vertexBuffers) {
  32103. this._vertexBuffers[kind].dispose();
  32104. }
  32105. this._vertexBuffers = {};
  32106. this._totalVertices = 0;
  32107. if (this._indexBuffer) {
  32108. this._engine._releaseBuffer(this._indexBuffer);
  32109. }
  32110. this._indexBuffer = null;
  32111. this._indices = [];
  32112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32113. this.delayLoadingFile = null;
  32114. this._delayLoadingFunction = null;
  32115. this._delayInfo = [];
  32116. this._boundingInfo = null;
  32117. this._scene.removeGeometry(this);
  32118. this._isDisposed = true;
  32119. };
  32120. Geometry.prototype.copy = function (id) {
  32121. var vertexData = new BABYLON.VertexData();
  32122. vertexData.indices = [];
  32123. var indices = this.getIndices();
  32124. if (indices) {
  32125. for (var index = 0; index < indices.length; index++) {
  32126. vertexData.indices.push(indices[index]);
  32127. }
  32128. }
  32129. var updatable = false;
  32130. var stopChecking = false;
  32131. var kind;
  32132. for (kind in this._vertexBuffers) {
  32133. // using slice() to make a copy of the array and not just reference it
  32134. var data = this.getVerticesData(kind);
  32135. if (data instanceof Float32Array) {
  32136. vertexData.set(new Float32Array(data), kind);
  32137. }
  32138. else {
  32139. vertexData.set(data.slice(0), kind);
  32140. }
  32141. if (!stopChecking) {
  32142. var vb = this.getVertexBuffer(kind);
  32143. if (vb) {
  32144. updatable = vb.isUpdatable();
  32145. stopChecking = !updatable;
  32146. }
  32147. }
  32148. }
  32149. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32150. geometry.delayLoadState = this.delayLoadState;
  32151. geometry.delayLoadingFile = this.delayLoadingFile;
  32152. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32153. for (kind in this._delayInfo) {
  32154. geometry._delayInfo = geometry._delayInfo || [];
  32155. geometry._delayInfo.push(kind);
  32156. }
  32157. // Bounding info
  32158. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32159. return geometry;
  32160. };
  32161. Geometry.prototype.serialize = function () {
  32162. var serializationObject = {};
  32163. serializationObject.id = this.id;
  32164. serializationObject.updatable = this._updatable;
  32165. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32166. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32167. }
  32168. return serializationObject;
  32169. };
  32170. Geometry.prototype.toNumberArray = function (origin) {
  32171. if (Array.isArray(origin)) {
  32172. return origin;
  32173. }
  32174. else {
  32175. return Array.prototype.slice.call(origin);
  32176. }
  32177. };
  32178. Geometry.prototype.serializeVerticeData = function () {
  32179. var serializationObject = this.serialize();
  32180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32181. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32182. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32183. serializationObject.positions._updatable = true;
  32184. }
  32185. }
  32186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32187. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32189. serializationObject.normals._updatable = true;
  32190. }
  32191. }
  32192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32193. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32195. serializationObject.uvs._updatable = true;
  32196. }
  32197. }
  32198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32199. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32201. serializationObject.uv2s._updatable = true;
  32202. }
  32203. }
  32204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32205. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32207. serializationObject.uv3s._updatable = true;
  32208. }
  32209. }
  32210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32211. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32212. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32213. serializationObject.uv4s._updatable = true;
  32214. }
  32215. }
  32216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32217. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32219. serializationObject.uv5s._updatable = true;
  32220. }
  32221. }
  32222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32223. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32224. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32225. serializationObject.uv6s._updatable = true;
  32226. }
  32227. }
  32228. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32229. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32230. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32231. serializationObject.colors._updatable = true;
  32232. }
  32233. }
  32234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32235. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32236. serializationObject.matricesIndices._isExpanded = true;
  32237. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32238. serializationObject.matricesIndices._updatable = true;
  32239. }
  32240. }
  32241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32242. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32243. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32244. serializationObject.matricesWeights._updatable = true;
  32245. }
  32246. }
  32247. serializationObject.indices = this.toNumberArray(this.getIndices());
  32248. return serializationObject;
  32249. };
  32250. // Statics
  32251. Geometry.ExtractFromMesh = function (mesh, id) {
  32252. var geometry = mesh._geometry;
  32253. if (!geometry) {
  32254. return null;
  32255. }
  32256. return geometry.copy(id);
  32257. };
  32258. /**
  32259. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32260. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32261. * Be aware Math.random() could cause collisions, but:
  32262. * "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"
  32263. */
  32264. Geometry.RandomId = function () {
  32265. return BABYLON.Tools.RandomId();
  32266. };
  32267. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32268. var scene = mesh.getScene();
  32269. // Geometry
  32270. var geometryId = parsedGeometry.geometryId;
  32271. if (geometryId) {
  32272. var geometry = scene.getGeometryByID(geometryId);
  32273. if (geometry) {
  32274. geometry.applyToMesh(mesh);
  32275. }
  32276. }
  32277. else if (parsedGeometry instanceof ArrayBuffer) {
  32278. var binaryInfo = mesh._binaryInfo;
  32279. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32280. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32281. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32282. }
  32283. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32284. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32285. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32286. }
  32287. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32288. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32289. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32290. }
  32291. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32292. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32293. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32294. }
  32295. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32296. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32297. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32298. }
  32299. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32300. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32301. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32302. }
  32303. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32304. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32305. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32306. }
  32307. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32308. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32309. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32310. }
  32311. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32312. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32313. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32314. }
  32315. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32316. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32317. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32318. }
  32319. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32320. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32321. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32322. }
  32323. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32324. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32325. mesh.setIndices(indicesData, null);
  32326. }
  32327. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32328. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32329. mesh.subMeshes = [];
  32330. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32331. var materialIndex = subMeshesData[(i * 5) + 0];
  32332. var verticesStart = subMeshesData[(i * 5) + 1];
  32333. var verticesCount = subMeshesData[(i * 5) + 2];
  32334. var indexStart = subMeshesData[(i * 5) + 3];
  32335. var indexCount = subMeshesData[(i * 5) + 4];
  32336. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32337. }
  32338. }
  32339. }
  32340. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32341. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32342. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32343. if (parsedGeometry.uvs) {
  32344. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32345. }
  32346. if (parsedGeometry.uvs2) {
  32347. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32348. }
  32349. if (parsedGeometry.uvs3) {
  32350. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32351. }
  32352. if (parsedGeometry.uvs4) {
  32353. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32354. }
  32355. if (parsedGeometry.uvs5) {
  32356. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32357. }
  32358. if (parsedGeometry.uvs6) {
  32359. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32360. }
  32361. if (parsedGeometry.colors) {
  32362. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32363. }
  32364. if (parsedGeometry.matricesIndices) {
  32365. if (!parsedGeometry.matricesIndices._isExpanded) {
  32366. var floatIndices = [];
  32367. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32368. var matricesIndex = parsedGeometry.matricesIndices[i];
  32369. floatIndices.push(matricesIndex & 0x000000FF);
  32370. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32371. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32372. floatIndices.push(matricesIndex >> 24);
  32373. }
  32374. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32375. }
  32376. else {
  32377. delete parsedGeometry.matricesIndices._isExpanded;
  32378. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32379. }
  32380. }
  32381. if (parsedGeometry.matricesIndicesExtra) {
  32382. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32383. var floatIndices = [];
  32384. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32385. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32386. floatIndices.push(matricesIndex & 0x000000FF);
  32387. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32388. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32389. floatIndices.push(matricesIndex >> 24);
  32390. }
  32391. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32392. }
  32393. else {
  32394. delete parsedGeometry.matricesIndices._isExpanded;
  32395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32396. }
  32397. }
  32398. if (parsedGeometry.matricesWeights) {
  32399. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32400. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32401. }
  32402. if (parsedGeometry.matricesWeightsExtra) {
  32403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32404. }
  32405. mesh.setIndices(parsedGeometry.indices, null);
  32406. }
  32407. // SubMeshes
  32408. if (parsedGeometry.subMeshes) {
  32409. mesh.subMeshes = [];
  32410. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32411. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32412. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32413. }
  32414. }
  32415. // Flat shading
  32416. if (mesh._shouldGenerateFlatShading) {
  32417. mesh.convertToFlatShadedMesh();
  32418. delete mesh._shouldGenerateFlatShading;
  32419. }
  32420. // Update
  32421. mesh.computeWorldMatrix(true);
  32422. // Octree
  32423. var sceneOctree = scene.selectionOctree;
  32424. if (sceneOctree !== undefined && sceneOctree !== null) {
  32425. sceneOctree.addMesh(mesh);
  32426. }
  32427. };
  32428. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32429. var epsilon = 1e-3;
  32430. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32431. return;
  32432. }
  32433. var noInfluenceBoneIndex = 0.0;
  32434. if (parsedGeometry.skeletonId > -1) {
  32435. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32436. if (!skeleton) {
  32437. return;
  32438. }
  32439. noInfluenceBoneIndex = skeleton.bones.length;
  32440. }
  32441. else {
  32442. return;
  32443. }
  32444. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32445. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32446. var matricesWeights = parsedGeometry.matricesWeights;
  32447. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32448. var influencers = parsedGeometry.numBoneInfluencer;
  32449. var size = matricesWeights.length;
  32450. for (var i = 0; i < size; i += 4) {
  32451. var weight = 0.0;
  32452. var firstZeroWeight = -1;
  32453. for (var j = 0; j < 4; j++) {
  32454. var w = matricesWeights[i + j];
  32455. weight += w;
  32456. if (w < epsilon && firstZeroWeight < 0) {
  32457. firstZeroWeight = j;
  32458. }
  32459. }
  32460. if (matricesWeightsExtra) {
  32461. for (var j = 0; j < 4; j++) {
  32462. var w = matricesWeightsExtra[i + j];
  32463. weight += w;
  32464. if (w < epsilon && firstZeroWeight < 0) {
  32465. firstZeroWeight = j + 4;
  32466. }
  32467. }
  32468. }
  32469. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32470. firstZeroWeight = influencers - 1;
  32471. }
  32472. if (weight > epsilon) {
  32473. var mweight = 1.0 / weight;
  32474. for (var j = 0; j < 4; j++) {
  32475. matricesWeights[i + j] *= mweight;
  32476. }
  32477. if (matricesWeightsExtra) {
  32478. for (var j = 0; j < 4; j++) {
  32479. matricesWeightsExtra[i + j] *= mweight;
  32480. }
  32481. }
  32482. }
  32483. else {
  32484. if (firstZeroWeight >= 4) {
  32485. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32486. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32487. }
  32488. else {
  32489. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32490. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32491. }
  32492. }
  32493. }
  32494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32495. if (parsedGeometry.matricesWeightsExtra) {
  32496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32497. }
  32498. };
  32499. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32500. if (scene.getGeometryByID(parsedVertexData.id)) {
  32501. return null; // null since geometry could be something else than a box...
  32502. }
  32503. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32504. if (BABYLON.Tags) {
  32505. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32506. }
  32507. if (parsedVertexData.delayLoadingFile) {
  32508. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32509. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32510. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32511. geometry._delayInfo = [];
  32512. if (parsedVertexData.hasUVs) {
  32513. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32514. }
  32515. if (parsedVertexData.hasUVs2) {
  32516. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32517. }
  32518. if (parsedVertexData.hasUVs3) {
  32519. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32520. }
  32521. if (parsedVertexData.hasUVs4) {
  32522. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32523. }
  32524. if (parsedVertexData.hasUVs5) {
  32525. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32526. }
  32527. if (parsedVertexData.hasUVs6) {
  32528. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32529. }
  32530. if (parsedVertexData.hasColors) {
  32531. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32532. }
  32533. if (parsedVertexData.hasMatricesIndices) {
  32534. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32535. }
  32536. if (parsedVertexData.hasMatricesWeights) {
  32537. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32538. }
  32539. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32540. }
  32541. else {
  32542. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32543. }
  32544. scene.pushGeometry(geometry, true);
  32545. return geometry;
  32546. };
  32547. return Geometry;
  32548. }());
  32549. BABYLON.Geometry = Geometry;
  32550. /////// Primitives //////////////////////////////////////////////
  32551. //export module Geometry.Primitives {
  32552. /// Abstract class
  32553. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32554. __extends(_PrimitiveGeometry, _super);
  32555. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32556. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32557. if (mesh === void 0) { mesh = null; }
  32558. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32559. _this._canBeRegenerated = _canBeRegenerated;
  32560. _this._beingRegenerated = true;
  32561. _this.regenerate();
  32562. _this._beingRegenerated = false;
  32563. return _this;
  32564. }
  32565. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32566. return this._canBeRegenerated;
  32567. };
  32568. _PrimitiveGeometry.prototype.regenerate = function () {
  32569. if (!this._canBeRegenerated) {
  32570. return;
  32571. }
  32572. this._beingRegenerated = true;
  32573. this.setAllVerticesData(this._regenerateVertexData(), false);
  32574. this._beingRegenerated = false;
  32575. };
  32576. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32577. return _super.prototype.copy.call(this, id);
  32578. };
  32579. // overrides
  32580. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32581. if (!this._beingRegenerated) {
  32582. return;
  32583. }
  32584. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32585. };
  32586. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32587. if (!this._beingRegenerated) {
  32588. return;
  32589. }
  32590. _super.prototype.setVerticesData.call(this, kind, data, false);
  32591. };
  32592. // to override
  32593. // protected
  32594. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32595. throw new Error("Abstract method");
  32596. };
  32597. _PrimitiveGeometry.prototype.copy = function (id) {
  32598. throw new Error("Must be overriden in sub-classes.");
  32599. };
  32600. _PrimitiveGeometry.prototype.serialize = function () {
  32601. var serializationObject = _super.prototype.serialize.call(this);
  32602. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32603. return serializationObject;
  32604. };
  32605. return _PrimitiveGeometry;
  32606. }(Geometry));
  32607. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32608. var RibbonGeometry = /** @class */ (function (_super) {
  32609. __extends(RibbonGeometry, _super);
  32610. // Members
  32611. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32612. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32613. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32614. _this.pathArray = pathArray;
  32615. _this.closeArray = closeArray;
  32616. _this.closePath = closePath;
  32617. _this.offset = offset;
  32618. _this.side = side;
  32619. return _this;
  32620. }
  32621. RibbonGeometry.prototype._regenerateVertexData = function () {
  32622. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32623. };
  32624. RibbonGeometry.prototype.copy = function (id) {
  32625. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32626. };
  32627. return RibbonGeometry;
  32628. }(_PrimitiveGeometry));
  32629. BABYLON.RibbonGeometry = RibbonGeometry;
  32630. var BoxGeometry = /** @class */ (function (_super) {
  32631. __extends(BoxGeometry, _super);
  32632. // Members
  32633. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32634. if (mesh === void 0) { mesh = null; }
  32635. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32636. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32637. _this.size = size;
  32638. _this.side = side;
  32639. return _this;
  32640. }
  32641. BoxGeometry.prototype._regenerateVertexData = function () {
  32642. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32643. };
  32644. BoxGeometry.prototype.copy = function (id) {
  32645. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32646. };
  32647. BoxGeometry.prototype.serialize = function () {
  32648. var serializationObject = _super.prototype.serialize.call(this);
  32649. serializationObject.size = this.size;
  32650. return serializationObject;
  32651. };
  32652. BoxGeometry.Parse = function (parsedBox, scene) {
  32653. if (scene.getGeometryByID(parsedBox.id)) {
  32654. return null; // null since geometry could be something else than a box...
  32655. }
  32656. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32657. if (BABYLON.Tags) {
  32658. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32659. }
  32660. scene.pushGeometry(box, true);
  32661. return box;
  32662. };
  32663. return BoxGeometry;
  32664. }(_PrimitiveGeometry));
  32665. BABYLON.BoxGeometry = BoxGeometry;
  32666. var SphereGeometry = /** @class */ (function (_super) {
  32667. __extends(SphereGeometry, _super);
  32668. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32669. if (mesh === void 0) { mesh = null; }
  32670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32672. _this.segments = segments;
  32673. _this.diameter = diameter;
  32674. _this.side = side;
  32675. return _this;
  32676. }
  32677. SphereGeometry.prototype._regenerateVertexData = function () {
  32678. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32679. };
  32680. SphereGeometry.prototype.copy = function (id) {
  32681. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32682. };
  32683. SphereGeometry.prototype.serialize = function () {
  32684. var serializationObject = _super.prototype.serialize.call(this);
  32685. serializationObject.segments = this.segments;
  32686. serializationObject.diameter = this.diameter;
  32687. return serializationObject;
  32688. };
  32689. SphereGeometry.Parse = function (parsedSphere, scene) {
  32690. if (scene.getGeometryByID(parsedSphere.id)) {
  32691. return null; // null since geometry could be something else than a sphere...
  32692. }
  32693. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32694. if (BABYLON.Tags) {
  32695. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32696. }
  32697. scene.pushGeometry(sphere, true);
  32698. return sphere;
  32699. };
  32700. return SphereGeometry;
  32701. }(_PrimitiveGeometry));
  32702. BABYLON.SphereGeometry = SphereGeometry;
  32703. var DiscGeometry = /** @class */ (function (_super) {
  32704. __extends(DiscGeometry, _super);
  32705. // Members
  32706. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32707. if (mesh === void 0) { mesh = null; }
  32708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32709. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32710. _this.radius = radius;
  32711. _this.tessellation = tessellation;
  32712. _this.side = side;
  32713. return _this;
  32714. }
  32715. DiscGeometry.prototype._regenerateVertexData = function () {
  32716. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32717. };
  32718. DiscGeometry.prototype.copy = function (id) {
  32719. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32720. };
  32721. return DiscGeometry;
  32722. }(_PrimitiveGeometry));
  32723. BABYLON.DiscGeometry = DiscGeometry;
  32724. var CylinderGeometry = /** @class */ (function (_super) {
  32725. __extends(CylinderGeometry, _super);
  32726. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32727. if (subdivisions === void 0) { subdivisions = 1; }
  32728. if (mesh === void 0) { mesh = null; }
  32729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32731. _this.height = height;
  32732. _this.diameterTop = diameterTop;
  32733. _this.diameterBottom = diameterBottom;
  32734. _this.tessellation = tessellation;
  32735. _this.subdivisions = subdivisions;
  32736. _this.side = side;
  32737. return _this;
  32738. }
  32739. CylinderGeometry.prototype._regenerateVertexData = function () {
  32740. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32741. };
  32742. CylinderGeometry.prototype.copy = function (id) {
  32743. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32744. };
  32745. CylinderGeometry.prototype.serialize = function () {
  32746. var serializationObject = _super.prototype.serialize.call(this);
  32747. serializationObject.height = this.height;
  32748. serializationObject.diameterTop = this.diameterTop;
  32749. serializationObject.diameterBottom = this.diameterBottom;
  32750. serializationObject.tessellation = this.tessellation;
  32751. return serializationObject;
  32752. };
  32753. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32754. if (scene.getGeometryByID(parsedCylinder.id)) {
  32755. return null; // null since geometry could be something else than a cylinder...
  32756. }
  32757. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32758. if (BABYLON.Tags) {
  32759. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32760. }
  32761. scene.pushGeometry(cylinder, true);
  32762. return cylinder;
  32763. };
  32764. return CylinderGeometry;
  32765. }(_PrimitiveGeometry));
  32766. BABYLON.CylinderGeometry = CylinderGeometry;
  32767. var TorusGeometry = /** @class */ (function (_super) {
  32768. __extends(TorusGeometry, _super);
  32769. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32770. if (mesh === void 0) { mesh = null; }
  32771. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32772. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32773. _this.diameter = diameter;
  32774. _this.thickness = thickness;
  32775. _this.tessellation = tessellation;
  32776. _this.side = side;
  32777. return _this;
  32778. }
  32779. TorusGeometry.prototype._regenerateVertexData = function () {
  32780. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32781. };
  32782. TorusGeometry.prototype.copy = function (id) {
  32783. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32784. };
  32785. TorusGeometry.prototype.serialize = function () {
  32786. var serializationObject = _super.prototype.serialize.call(this);
  32787. serializationObject.diameter = this.diameter;
  32788. serializationObject.thickness = this.thickness;
  32789. serializationObject.tessellation = this.tessellation;
  32790. return serializationObject;
  32791. };
  32792. TorusGeometry.Parse = function (parsedTorus, scene) {
  32793. if (scene.getGeometryByID(parsedTorus.id)) {
  32794. return null; // null since geometry could be something else than a torus...
  32795. }
  32796. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32797. if (BABYLON.Tags) {
  32798. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32799. }
  32800. scene.pushGeometry(torus, true);
  32801. return torus;
  32802. };
  32803. return TorusGeometry;
  32804. }(_PrimitiveGeometry));
  32805. BABYLON.TorusGeometry = TorusGeometry;
  32806. var GroundGeometry = /** @class */ (function (_super) {
  32807. __extends(GroundGeometry, _super);
  32808. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32809. if (mesh === void 0) { mesh = null; }
  32810. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32811. _this.width = width;
  32812. _this.height = height;
  32813. _this.subdivisions = subdivisions;
  32814. return _this;
  32815. }
  32816. GroundGeometry.prototype._regenerateVertexData = function () {
  32817. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32818. };
  32819. GroundGeometry.prototype.copy = function (id) {
  32820. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32821. };
  32822. GroundGeometry.prototype.serialize = function () {
  32823. var serializationObject = _super.prototype.serialize.call(this);
  32824. serializationObject.width = this.width;
  32825. serializationObject.height = this.height;
  32826. serializationObject.subdivisions = this.subdivisions;
  32827. return serializationObject;
  32828. };
  32829. GroundGeometry.Parse = function (parsedGround, scene) {
  32830. if (scene.getGeometryByID(parsedGround.id)) {
  32831. return null; // null since geometry could be something else than a ground...
  32832. }
  32833. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32834. if (BABYLON.Tags) {
  32835. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32836. }
  32837. scene.pushGeometry(ground, true);
  32838. return ground;
  32839. };
  32840. return GroundGeometry;
  32841. }(_PrimitiveGeometry));
  32842. BABYLON.GroundGeometry = GroundGeometry;
  32843. var TiledGroundGeometry = /** @class */ (function (_super) {
  32844. __extends(TiledGroundGeometry, _super);
  32845. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32846. if (mesh === void 0) { mesh = null; }
  32847. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32848. _this.xmin = xmin;
  32849. _this.zmin = zmin;
  32850. _this.xmax = xmax;
  32851. _this.zmax = zmax;
  32852. _this.subdivisions = subdivisions;
  32853. _this.precision = precision;
  32854. return _this;
  32855. }
  32856. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32857. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32858. };
  32859. TiledGroundGeometry.prototype.copy = function (id) {
  32860. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32861. };
  32862. return TiledGroundGeometry;
  32863. }(_PrimitiveGeometry));
  32864. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32865. var PlaneGeometry = /** @class */ (function (_super) {
  32866. __extends(PlaneGeometry, _super);
  32867. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32868. if (mesh === void 0) { mesh = null; }
  32869. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32870. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32871. _this.size = size;
  32872. _this.side = side;
  32873. return _this;
  32874. }
  32875. PlaneGeometry.prototype._regenerateVertexData = function () {
  32876. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32877. };
  32878. PlaneGeometry.prototype.copy = function (id) {
  32879. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32880. };
  32881. PlaneGeometry.prototype.serialize = function () {
  32882. var serializationObject = _super.prototype.serialize.call(this);
  32883. serializationObject.size = this.size;
  32884. return serializationObject;
  32885. };
  32886. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32887. if (scene.getGeometryByID(parsedPlane.id)) {
  32888. return null; // null since geometry could be something else than a ground...
  32889. }
  32890. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32891. if (BABYLON.Tags) {
  32892. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32893. }
  32894. scene.pushGeometry(plane, true);
  32895. return plane;
  32896. };
  32897. return PlaneGeometry;
  32898. }(_PrimitiveGeometry));
  32899. BABYLON.PlaneGeometry = PlaneGeometry;
  32900. var TorusKnotGeometry = /** @class */ (function (_super) {
  32901. __extends(TorusKnotGeometry, _super);
  32902. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32903. if (mesh === void 0) { mesh = null; }
  32904. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32905. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32906. _this.radius = radius;
  32907. _this.tube = tube;
  32908. _this.radialSegments = radialSegments;
  32909. _this.tubularSegments = tubularSegments;
  32910. _this.p = p;
  32911. _this.q = q;
  32912. _this.side = side;
  32913. return _this;
  32914. }
  32915. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32916. 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 });
  32917. };
  32918. TorusKnotGeometry.prototype.copy = function (id) {
  32919. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32920. };
  32921. TorusKnotGeometry.prototype.serialize = function () {
  32922. var serializationObject = _super.prototype.serialize.call(this);
  32923. serializationObject.radius = this.radius;
  32924. serializationObject.tube = this.tube;
  32925. serializationObject.radialSegments = this.radialSegments;
  32926. serializationObject.tubularSegments = this.tubularSegments;
  32927. serializationObject.p = this.p;
  32928. serializationObject.q = this.q;
  32929. return serializationObject;
  32930. };
  32931. ;
  32932. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32933. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32934. return null; // null since geometry could be something else than a ground...
  32935. }
  32936. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32937. if (BABYLON.Tags) {
  32938. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32939. }
  32940. scene.pushGeometry(torusKnot, true);
  32941. return torusKnot;
  32942. };
  32943. return TorusKnotGeometry;
  32944. }(_PrimitiveGeometry));
  32945. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32946. //}
  32947. })(BABYLON || (BABYLON = {}));
  32948. //# sourceMappingURL=babylon.geometry.js.map
  32949. var BABYLON;
  32950. (function (BABYLON) {
  32951. var PostProcessManager = /** @class */ (function () {
  32952. function PostProcessManager(scene) {
  32953. this._vertexBuffers = {};
  32954. this._scene = scene;
  32955. }
  32956. PostProcessManager.prototype._prepareBuffers = function () {
  32957. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32958. return;
  32959. }
  32960. // VBO
  32961. var vertices = [];
  32962. vertices.push(1, 1);
  32963. vertices.push(-1, 1);
  32964. vertices.push(-1, -1);
  32965. vertices.push(1, -1);
  32966. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32967. this._buildIndexBuffer();
  32968. };
  32969. PostProcessManager.prototype._buildIndexBuffer = function () {
  32970. // Indices
  32971. var indices = [];
  32972. indices.push(0);
  32973. indices.push(1);
  32974. indices.push(2);
  32975. indices.push(0);
  32976. indices.push(2);
  32977. indices.push(3);
  32978. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32979. };
  32980. PostProcessManager.prototype._rebuild = function () {
  32981. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32982. if (!vb) {
  32983. return;
  32984. }
  32985. vb._rebuild();
  32986. this._buildIndexBuffer();
  32987. };
  32988. // Methods
  32989. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32990. if (sourceTexture === void 0) { sourceTexture = null; }
  32991. if (postProcesses === void 0) { postProcesses = null; }
  32992. var camera = this._scene.activeCamera;
  32993. if (!camera) {
  32994. return false;
  32995. }
  32996. var postProcesses = postProcesses || camera._postProcesses;
  32997. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32998. return false;
  32999. }
  33000. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33001. return true;
  33002. };
  33003. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33004. if (targetTexture === void 0) { targetTexture = null; }
  33005. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33006. var engine = this._scene.getEngine();
  33007. for (var index = 0; index < postProcesses.length; index++) {
  33008. if (index < postProcesses.length - 1) {
  33009. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33010. }
  33011. else {
  33012. if (targetTexture) {
  33013. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33014. }
  33015. else {
  33016. engine.restoreDefaultFramebuffer();
  33017. }
  33018. }
  33019. var pp = postProcesses[index];
  33020. var effect = pp.apply();
  33021. if (effect) {
  33022. pp.onBeforeRenderObservable.notifyObservers(effect);
  33023. // VBOs
  33024. this._prepareBuffers();
  33025. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33026. // Draw order
  33027. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33028. pp.onAfterRenderObservable.notifyObservers(effect);
  33029. }
  33030. }
  33031. // Restore depth buffer
  33032. engine.setDepthBuffer(true);
  33033. engine.setDepthWrite(true);
  33034. };
  33035. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33036. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33037. var camera = this._scene.activeCamera;
  33038. if (!camera) {
  33039. return;
  33040. }
  33041. postProcesses = postProcesses || camera._postProcesses;
  33042. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33043. return;
  33044. }
  33045. var engine = this._scene.getEngine();
  33046. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33047. if (index < len - 1) {
  33048. postProcesses[index + 1].activate(camera, targetTexture);
  33049. }
  33050. else {
  33051. if (targetTexture) {
  33052. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33053. }
  33054. else {
  33055. engine.restoreDefaultFramebuffer();
  33056. }
  33057. }
  33058. if (doNotPresent) {
  33059. break;
  33060. }
  33061. var pp = postProcesses[index];
  33062. var effect = pp.apply();
  33063. if (effect) {
  33064. pp.onBeforeRenderObservable.notifyObservers(effect);
  33065. // VBOs
  33066. this._prepareBuffers();
  33067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33068. // Draw order
  33069. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33070. pp.onAfterRenderObservable.notifyObservers(effect);
  33071. }
  33072. }
  33073. // Restore states
  33074. engine.setDepthBuffer(true);
  33075. engine.setDepthWrite(true);
  33076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33077. };
  33078. PostProcessManager.prototype.dispose = function () {
  33079. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33080. if (buffer) {
  33081. buffer.dispose();
  33082. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33083. }
  33084. if (this._indexBuffer) {
  33085. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33086. this._indexBuffer = null;
  33087. }
  33088. };
  33089. return PostProcessManager;
  33090. }());
  33091. BABYLON.PostProcessManager = PostProcessManager;
  33092. })(BABYLON || (BABYLON = {}));
  33093. //# sourceMappingURL=babylon.postProcessManager.js.map
  33094. var BABYLON;
  33095. (function (BABYLON) {
  33096. /**
  33097. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33098. */
  33099. var PerformanceMonitor = /** @class */ (function () {
  33100. /**
  33101. * constructor
  33102. * @param frameSampleSize The number of samples required to saturate the sliding window
  33103. */
  33104. function PerformanceMonitor(frameSampleSize) {
  33105. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33106. this._enabled = true;
  33107. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33108. }
  33109. /**
  33110. * Samples current frame
  33111. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33112. */
  33113. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33114. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33115. if (!this._enabled)
  33116. return;
  33117. if (this._lastFrameTimeMs != null) {
  33118. var dt = timeMs - this._lastFrameTimeMs;
  33119. this._rollingFrameTime.add(dt);
  33120. }
  33121. this._lastFrameTimeMs = timeMs;
  33122. };
  33123. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33124. /**
  33125. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33126. * @return Average frame time in milliseconds
  33127. */
  33128. get: function () {
  33129. return this._rollingFrameTime.average;
  33130. },
  33131. enumerable: true,
  33132. configurable: true
  33133. });
  33134. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33135. /**
  33136. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33137. * @return Frame time variance in milliseconds squared
  33138. */
  33139. get: function () {
  33140. return this._rollingFrameTime.variance;
  33141. },
  33142. enumerable: true,
  33143. configurable: true
  33144. });
  33145. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33146. /**
  33147. * Returns the frame time of the most recent frame
  33148. * @return Frame time in milliseconds
  33149. */
  33150. get: function () {
  33151. return this._rollingFrameTime.history(0);
  33152. },
  33153. enumerable: true,
  33154. configurable: true
  33155. });
  33156. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33157. /**
  33158. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33159. * @return Framerate in frames per second
  33160. */
  33161. get: function () {
  33162. return 1000.0 / this._rollingFrameTime.average;
  33163. },
  33164. enumerable: true,
  33165. configurable: true
  33166. });
  33167. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33168. /**
  33169. * Returns the average framerate in frames per second using the most recent frame time
  33170. * @return Framerate in frames per second
  33171. */
  33172. get: function () {
  33173. var history = this._rollingFrameTime.history(0);
  33174. if (history === 0) {
  33175. return 0;
  33176. }
  33177. return 1000.0 / history;
  33178. },
  33179. enumerable: true,
  33180. configurable: true
  33181. });
  33182. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33183. /**
  33184. * Returns true if enough samples have been taken to completely fill the sliding window
  33185. * @return true if saturated
  33186. */
  33187. get: function () {
  33188. return this._rollingFrameTime.isSaturated();
  33189. },
  33190. enumerable: true,
  33191. configurable: true
  33192. });
  33193. /**
  33194. * Enables contributions to the sliding window sample set
  33195. */
  33196. PerformanceMonitor.prototype.enable = function () {
  33197. this._enabled = true;
  33198. };
  33199. /**
  33200. * Disables contributions to the sliding window sample set
  33201. * Samples will not be interpolated over the disabled period
  33202. */
  33203. PerformanceMonitor.prototype.disable = function () {
  33204. this._enabled = false;
  33205. //clear last sample to avoid interpolating over the disabled period when next enabled
  33206. this._lastFrameTimeMs = null;
  33207. };
  33208. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33209. /**
  33210. * Returns true if sampling is enabled
  33211. * @return true if enabled
  33212. */
  33213. get: function () {
  33214. return this._enabled;
  33215. },
  33216. enumerable: true,
  33217. configurable: true
  33218. });
  33219. /**
  33220. * Resets performance monitor
  33221. */
  33222. PerformanceMonitor.prototype.reset = function () {
  33223. //clear last sample to avoid interpolating over the disabled period when next enabled
  33224. this._lastFrameTimeMs = null;
  33225. //wipe record
  33226. this._rollingFrameTime.reset();
  33227. };
  33228. return PerformanceMonitor;
  33229. }());
  33230. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33231. /**
  33232. * RollingAverage
  33233. *
  33234. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33235. */
  33236. var RollingAverage = /** @class */ (function () {
  33237. /**
  33238. * constructor
  33239. * @param length The number of samples required to saturate the sliding window
  33240. */
  33241. function RollingAverage(length) {
  33242. this._samples = new Array(length);
  33243. this.reset();
  33244. }
  33245. /**
  33246. * Adds a sample to the sample set
  33247. * @param v The sample value
  33248. */
  33249. RollingAverage.prototype.add = function (v) {
  33250. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33251. var delta;
  33252. //we need to check if we've already wrapped round
  33253. if (this.isSaturated()) {
  33254. //remove bottom of stack from mean
  33255. var bottomValue = this._samples[this._pos];
  33256. delta = bottomValue - this.average;
  33257. this.average -= delta / (this._sampleCount - 1);
  33258. this._m2 -= delta * (bottomValue - this.average);
  33259. }
  33260. else {
  33261. this._sampleCount++;
  33262. }
  33263. //add new value to mean
  33264. delta = v - this.average;
  33265. this.average += delta / (this._sampleCount);
  33266. this._m2 += delta * (v - this.average);
  33267. //set the new variance
  33268. this.variance = this._m2 / (this._sampleCount - 1);
  33269. this._samples[this._pos] = v;
  33270. this._pos++;
  33271. this._pos %= this._samples.length; //positive wrap around
  33272. };
  33273. /**
  33274. * Returns previously added values or null if outside of history or outside the sliding window domain
  33275. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33276. * @return Value previously recorded with add() or null if outside of range
  33277. */
  33278. RollingAverage.prototype.history = function (i) {
  33279. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33280. return 0;
  33281. }
  33282. var i0 = this._wrapPosition(this._pos - 1.0);
  33283. return this._samples[this._wrapPosition(i0 - i)];
  33284. };
  33285. /**
  33286. * Returns true if enough samples have been taken to completely fill the sliding window
  33287. * @return true if sample-set saturated
  33288. */
  33289. RollingAverage.prototype.isSaturated = function () {
  33290. return this._sampleCount >= this._samples.length;
  33291. };
  33292. /**
  33293. * Resets the rolling average (equivalent to 0 samples taken so far)
  33294. */
  33295. RollingAverage.prototype.reset = function () {
  33296. this.average = 0;
  33297. this.variance = 0;
  33298. this._sampleCount = 0;
  33299. this._pos = 0;
  33300. this._m2 = 0;
  33301. };
  33302. /**
  33303. * Wraps a value around the sample range boundaries
  33304. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33305. * @return Wrapped position in sample range
  33306. */
  33307. RollingAverage.prototype._wrapPosition = function (i) {
  33308. var max = this._samples.length;
  33309. return ((i % max) + max) % max;
  33310. };
  33311. return RollingAverage;
  33312. }());
  33313. BABYLON.RollingAverage = RollingAverage;
  33314. })(BABYLON || (BABYLON = {}));
  33315. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33316. var BABYLON;
  33317. (function (BABYLON) {
  33318. /**
  33319. * This groups together the common properties used for image processing either in direct forward pass
  33320. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33321. * or not.
  33322. */
  33323. var ImageProcessingConfiguration = /** @class */ (function () {
  33324. function ImageProcessingConfiguration() {
  33325. /**
  33326. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33327. */
  33328. this.colorCurves = new BABYLON.ColorCurves();
  33329. this._colorCurvesEnabled = false;
  33330. this._colorGradingEnabled = false;
  33331. this._colorGradingWithGreenDepth = true;
  33332. this._colorGradingBGR = true;
  33333. this._exposure = 1.0;
  33334. this._toneMappingEnabled = false;
  33335. this._contrast = 1.0;
  33336. /**
  33337. * Vignette stretch size.
  33338. */
  33339. this.vignetteStretch = 0;
  33340. /**
  33341. * Vignette centre X Offset.
  33342. */
  33343. this.vignetteCentreX = 0;
  33344. /**
  33345. * Vignette centre Y Offset.
  33346. */
  33347. this.vignetteCentreY = 0;
  33348. /**
  33349. * Vignette weight or intensity of the vignette effect.
  33350. */
  33351. this.vignetteWeight = 1.5;
  33352. /**
  33353. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33354. * if vignetteEnabled is set to true.
  33355. */
  33356. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33357. /**
  33358. * Camera field of view used by the Vignette effect.
  33359. */
  33360. this.vignetteCameraFov = 0.5;
  33361. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33362. this._vignetteEnabled = false;
  33363. this._applyByPostProcess = false;
  33364. this._isEnabled = true;
  33365. /**
  33366. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33367. * @type {BABYLON.Observable}
  33368. */
  33369. this.onUpdateParameters = new BABYLON.Observable();
  33370. }
  33371. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33372. /**
  33373. * Gets wether the color curves effect is enabled.
  33374. */
  33375. get: function () {
  33376. return this._colorCurvesEnabled;
  33377. },
  33378. /**
  33379. * Sets wether the color curves effect is enabled.
  33380. */
  33381. set: function (value) {
  33382. if (this._colorCurvesEnabled === value) {
  33383. return;
  33384. }
  33385. this._colorCurvesEnabled = value;
  33386. this._updateParameters();
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33392. /**
  33393. * Gets wether the color grading effect is enabled.
  33394. */
  33395. get: function () {
  33396. return this._colorGradingEnabled;
  33397. },
  33398. /**
  33399. * Sets wether the color grading effect is enabled.
  33400. */
  33401. set: function (value) {
  33402. if (this._colorGradingEnabled === value) {
  33403. return;
  33404. }
  33405. this._colorGradingEnabled = value;
  33406. this._updateParameters();
  33407. },
  33408. enumerable: true,
  33409. configurable: true
  33410. });
  33411. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33412. /**
  33413. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33414. */
  33415. get: function () {
  33416. return this._colorGradingWithGreenDepth;
  33417. },
  33418. /**
  33419. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33420. */
  33421. set: function (value) {
  33422. if (this._colorGradingWithGreenDepth === value) {
  33423. return;
  33424. }
  33425. this._colorGradingWithGreenDepth = value;
  33426. this._updateParameters();
  33427. },
  33428. enumerable: true,
  33429. configurable: true
  33430. });
  33431. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33432. /**
  33433. * Gets wether the color grading texture contains BGR values.
  33434. */
  33435. get: function () {
  33436. return this._colorGradingBGR;
  33437. },
  33438. /**
  33439. * Sets wether the color grading texture contains BGR values.
  33440. */
  33441. set: function (value) {
  33442. if (this._colorGradingBGR === value) {
  33443. return;
  33444. }
  33445. this._colorGradingBGR = value;
  33446. this._updateParameters();
  33447. },
  33448. enumerable: true,
  33449. configurable: true
  33450. });
  33451. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33452. /**
  33453. * Gets the Exposure used in the effect.
  33454. */
  33455. get: function () {
  33456. return this._exposure;
  33457. },
  33458. /**
  33459. * Sets the Exposure used in the effect.
  33460. */
  33461. set: function (value) {
  33462. if (this._exposure === value) {
  33463. return;
  33464. }
  33465. this._exposure = value;
  33466. this._updateParameters();
  33467. },
  33468. enumerable: true,
  33469. configurable: true
  33470. });
  33471. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33472. /**
  33473. * Gets wether the tone mapping effect is enabled.
  33474. */
  33475. get: function () {
  33476. return this._toneMappingEnabled;
  33477. },
  33478. /**
  33479. * Sets wether the tone mapping effect is enabled.
  33480. */
  33481. set: function (value) {
  33482. if (this._toneMappingEnabled === value) {
  33483. return;
  33484. }
  33485. this._toneMappingEnabled = value;
  33486. this._updateParameters();
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33492. /**
  33493. * Gets the contrast used in the effect.
  33494. */
  33495. get: function () {
  33496. return this._contrast;
  33497. },
  33498. /**
  33499. * Sets the contrast used in the effect.
  33500. */
  33501. set: function (value) {
  33502. if (this._contrast === value) {
  33503. return;
  33504. }
  33505. this._contrast = value;
  33506. this._updateParameters();
  33507. },
  33508. enumerable: true,
  33509. configurable: true
  33510. });
  33511. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33512. /**
  33513. * Gets the vignette blend mode allowing different kind of effect.
  33514. */
  33515. get: function () {
  33516. return this._vignetteBlendMode;
  33517. },
  33518. /**
  33519. * Sets the vignette blend mode allowing different kind of effect.
  33520. */
  33521. set: function (value) {
  33522. if (this._vignetteBlendMode === value) {
  33523. return;
  33524. }
  33525. this._vignetteBlendMode = value;
  33526. this._updateParameters();
  33527. },
  33528. enumerable: true,
  33529. configurable: true
  33530. });
  33531. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33532. /**
  33533. * Gets wether the vignette effect is enabled.
  33534. */
  33535. get: function () {
  33536. return this._vignetteEnabled;
  33537. },
  33538. /**
  33539. * Sets wether the vignette effect is enabled.
  33540. */
  33541. set: function (value) {
  33542. if (this._vignetteEnabled === value) {
  33543. return;
  33544. }
  33545. this._vignetteEnabled = value;
  33546. this._updateParameters();
  33547. },
  33548. enumerable: true,
  33549. configurable: true
  33550. });
  33551. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33552. /**
  33553. * Gets wether the image processing is applied through a post process or not.
  33554. */
  33555. get: function () {
  33556. return this._applyByPostProcess;
  33557. },
  33558. /**
  33559. * Sets wether the image processing is applied through a post process or not.
  33560. */
  33561. set: function (value) {
  33562. if (this._applyByPostProcess === value) {
  33563. return;
  33564. }
  33565. this._applyByPostProcess = value;
  33566. this._updateParameters();
  33567. },
  33568. enumerable: true,
  33569. configurable: true
  33570. });
  33571. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33572. /**
  33573. * Gets wether the image processing is enabled or not.
  33574. */
  33575. get: function () {
  33576. return this._isEnabled;
  33577. },
  33578. /**
  33579. * Sets wether the image processing is enabled or not.
  33580. */
  33581. set: function (value) {
  33582. if (this._isEnabled === value) {
  33583. return;
  33584. }
  33585. this._isEnabled = value;
  33586. this._updateParameters();
  33587. },
  33588. enumerable: true,
  33589. configurable: true
  33590. });
  33591. /**
  33592. * Method called each time the image processing information changes requires to recompile the effect.
  33593. */
  33594. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33595. this.onUpdateParameters.notifyObservers(this);
  33596. };
  33597. ImageProcessingConfiguration.prototype.getClassName = function () {
  33598. return "ImageProcessingConfiguration";
  33599. };
  33600. /**
  33601. * Prepare the list of uniforms associated with the Image Processing effects.
  33602. * @param uniformsList The list of uniforms used in the effect
  33603. * @param defines the list of defines currently in use
  33604. */
  33605. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33606. if (defines.EXPOSURE) {
  33607. uniforms.push("exposureLinear");
  33608. }
  33609. if (defines.CONTRAST) {
  33610. uniforms.push("contrast");
  33611. }
  33612. if (defines.COLORGRADING) {
  33613. uniforms.push("colorTransformSettings");
  33614. }
  33615. if (defines.VIGNETTE) {
  33616. uniforms.push("vInverseScreenSize");
  33617. uniforms.push("vignetteSettings1");
  33618. uniforms.push("vignetteSettings2");
  33619. }
  33620. if (defines.COLORCURVES) {
  33621. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33622. }
  33623. };
  33624. /**
  33625. * Prepare the list of samplers associated with the Image Processing effects.
  33626. * @param uniformsList The list of uniforms used in the effect
  33627. * @param defines the list of defines currently in use
  33628. */
  33629. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33630. if (defines.COLORGRADING) {
  33631. samplersList.push("txColorTransform");
  33632. }
  33633. };
  33634. /**
  33635. * Prepare the list of defines associated to the shader.
  33636. * @param defines the list of defines to complete
  33637. */
  33638. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33639. if (forPostProcess === void 0) { forPostProcess = false; }
  33640. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33641. defines.VIGNETTE = false;
  33642. defines.TONEMAPPING = false;
  33643. defines.CONTRAST = false;
  33644. defines.EXPOSURE = false;
  33645. defines.COLORCURVES = false;
  33646. defines.COLORGRADING = false;
  33647. defines.COLORGRADING3D = false;
  33648. defines.IMAGEPROCESSING = false;
  33649. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33650. return;
  33651. }
  33652. defines.VIGNETTE = this.vignetteEnabled;
  33653. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33654. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33655. defines.TONEMAPPING = this.toneMappingEnabled;
  33656. defines.CONTRAST = (this.contrast !== 1.0);
  33657. defines.EXPOSURE = (this.exposure !== 1.0);
  33658. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33659. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33660. if (defines.COLORGRADING) {
  33661. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33662. }
  33663. else {
  33664. defines.COLORGRADING3D = false;
  33665. }
  33666. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33667. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33668. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33669. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33670. };
  33671. /**
  33672. * Returns true if all the image processing information are ready.
  33673. */
  33674. ImageProcessingConfiguration.prototype.isReady = function () {
  33675. // Color Grading texure can not be none blocking.
  33676. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33677. };
  33678. /**
  33679. * Binds the image processing to the shader.
  33680. * @param effect The effect to bind to
  33681. */
  33682. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33683. if (aspectRatio === void 0) { aspectRatio = 1; }
  33684. // Color Curves
  33685. if (this._colorCurvesEnabled && this.colorCurves) {
  33686. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33687. }
  33688. // Vignette
  33689. if (this._vignetteEnabled) {
  33690. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33691. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33692. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33693. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33694. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33695. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33696. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33697. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33698. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33699. var vignettePower = -2.0 * this.vignetteWeight;
  33700. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33701. }
  33702. // Exposure
  33703. effect.setFloat("exposureLinear", this.exposure);
  33704. // Contrast
  33705. effect.setFloat("contrast", this.contrast);
  33706. // Color transform settings
  33707. if (this.colorGradingTexture) {
  33708. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33709. var textureSize = this.colorGradingTexture.getSize().height;
  33710. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33711. 0.5 / textureSize, // textureOffset
  33712. textureSize, // textureSize
  33713. this.colorGradingTexture.level // weight
  33714. );
  33715. }
  33716. };
  33717. /**
  33718. * Clones the current image processing instance.
  33719. * @return The cloned image processing
  33720. */
  33721. ImageProcessingConfiguration.prototype.clone = function () {
  33722. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33723. };
  33724. /**
  33725. * Serializes the current image processing instance to a json representation.
  33726. * @return a JSON representation
  33727. */
  33728. ImageProcessingConfiguration.prototype.serialize = function () {
  33729. return BABYLON.SerializationHelper.Serialize(this);
  33730. };
  33731. /**
  33732. * Parses the image processing from a json representation.
  33733. * @param source the JSON source to parse
  33734. * @return The parsed image processing
  33735. */
  33736. ImageProcessingConfiguration.Parse = function (source) {
  33737. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33738. };
  33739. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33740. /**
  33741. * Used to apply the vignette as a mix with the pixel color.
  33742. */
  33743. get: function () {
  33744. return this._VIGNETTEMODE_MULTIPLY;
  33745. },
  33746. enumerable: true,
  33747. configurable: true
  33748. });
  33749. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33750. /**
  33751. * Used to apply the vignette as a replacement of the pixel color.
  33752. */
  33753. get: function () {
  33754. return this._VIGNETTEMODE_OPAQUE;
  33755. },
  33756. enumerable: true,
  33757. configurable: true
  33758. });
  33759. // Static constants associated to the image processing.
  33760. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33761. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33762. __decorate([
  33763. BABYLON.serializeAsColorCurves()
  33764. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33765. __decorate([
  33766. BABYLON.serialize()
  33767. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33768. __decorate([
  33769. BABYLON.serializeAsTexture()
  33770. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33771. __decorate([
  33772. BABYLON.serialize()
  33773. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33774. __decorate([
  33775. BABYLON.serialize()
  33776. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33777. __decorate([
  33778. BABYLON.serialize()
  33779. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33780. __decorate([
  33781. BABYLON.serialize()
  33782. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33783. __decorate([
  33784. BABYLON.serialize()
  33785. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33786. __decorate([
  33787. BABYLON.serialize()
  33788. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33789. __decorate([
  33790. BABYLON.serialize()
  33791. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33792. __decorate([
  33793. BABYLON.serialize()
  33794. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33795. __decorate([
  33796. BABYLON.serialize()
  33797. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33798. __decorate([
  33799. BABYLON.serialize()
  33800. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33801. __decorate([
  33802. BABYLON.serializeAsColor4()
  33803. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33804. __decorate([
  33805. BABYLON.serialize()
  33806. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33807. __decorate([
  33808. BABYLON.serialize()
  33809. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33810. __decorate([
  33811. BABYLON.serialize()
  33812. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33813. __decorate([
  33814. BABYLON.serialize()
  33815. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33816. __decorate([
  33817. BABYLON.serialize()
  33818. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33819. return ImageProcessingConfiguration;
  33820. }());
  33821. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33822. })(BABYLON || (BABYLON = {}));
  33823. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33824. var BABYLON;
  33825. (function (BABYLON) {
  33826. /**
  33827. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33828. * It can help converting any input color in a desired output one. This can then be used to create effects
  33829. * from sepia, black and white to sixties or futuristic rendering...
  33830. *
  33831. * The only supported format is currently 3dl.
  33832. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33833. */
  33834. var ColorGradingTexture = /** @class */ (function (_super) {
  33835. __extends(ColorGradingTexture, _super);
  33836. /**
  33837. * Instantiates a ColorGradingTexture from the following parameters.
  33838. *
  33839. * @param url The location of the color gradind data (currently only supporting 3dl)
  33840. * @param scene The scene the texture will be used in
  33841. */
  33842. function ColorGradingTexture(url, scene) {
  33843. var _this = _super.call(this, scene) || this;
  33844. if (!url) {
  33845. return _this;
  33846. }
  33847. _this._engine = scene.getEngine();
  33848. _this._textureMatrix = BABYLON.Matrix.Identity();
  33849. _this.name = url;
  33850. _this.url = url;
  33851. _this.hasAlpha = false;
  33852. _this.isCube = false;
  33853. _this.is3D = _this._engine.webGLVersion > 1;
  33854. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33855. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33856. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33857. _this.anisotropicFilteringLevel = 1;
  33858. _this._texture = _this._getFromCache(url, true);
  33859. if (!_this._texture) {
  33860. if (!scene.useDelayedTextureLoading) {
  33861. _this.loadTexture();
  33862. }
  33863. else {
  33864. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33865. }
  33866. }
  33867. return _this;
  33868. }
  33869. /**
  33870. * Returns the texture matrix used in most of the material.
  33871. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33872. */
  33873. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33874. return this._textureMatrix;
  33875. };
  33876. /**
  33877. * Occurs when the file being loaded is a .3dl LUT file.
  33878. */
  33879. ColorGradingTexture.prototype.load3dlTexture = function () {
  33880. var engine = this._engine;
  33881. var texture;
  33882. if (engine.webGLVersion === 1) {
  33883. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33884. }
  33885. else {
  33886. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33887. }
  33888. this._texture = texture;
  33889. var callback = function (text) {
  33890. if (typeof text !== "string") {
  33891. return;
  33892. }
  33893. var data = null;
  33894. var tempData = null;
  33895. var line;
  33896. var lines = text.split('\n');
  33897. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33898. var maxColor = 0;
  33899. for (var i = 0; i < lines.length; i++) {
  33900. line = lines[i];
  33901. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33902. continue;
  33903. if (line.indexOf('#') === 0)
  33904. continue;
  33905. var words = line.split(" ");
  33906. if (size === 0) {
  33907. // Number of space + one
  33908. size = words.length;
  33909. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33910. tempData = new Float32Array(size * size * size * 4);
  33911. continue;
  33912. }
  33913. if (size != 0) {
  33914. var r = Math.max(parseInt(words[0]), 0);
  33915. var g = Math.max(parseInt(words[1]), 0);
  33916. var b = Math.max(parseInt(words[2]), 0);
  33917. maxColor = Math.max(r, maxColor);
  33918. maxColor = Math.max(g, maxColor);
  33919. maxColor = Math.max(b, maxColor);
  33920. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33921. if (tempData) {
  33922. tempData[pixelStorageIndex + 0] = r;
  33923. tempData[pixelStorageIndex + 1] = g;
  33924. tempData[pixelStorageIndex + 2] = b;
  33925. }
  33926. pixelIndexSlice++;
  33927. if (pixelIndexSlice % size == 0) {
  33928. pixelIndexH++;
  33929. pixelIndexSlice = 0;
  33930. if (pixelIndexH % size == 0) {
  33931. pixelIndexW++;
  33932. pixelIndexH = 0;
  33933. }
  33934. }
  33935. }
  33936. }
  33937. if (tempData && data) {
  33938. for (var i = 0; i < tempData.length; i++) {
  33939. if (i > 0 && (i + 1) % 4 === 0) {
  33940. data[i] = 255;
  33941. }
  33942. else {
  33943. var value = tempData[i];
  33944. data[i] = (value / maxColor * 255);
  33945. }
  33946. }
  33947. }
  33948. if (texture.is3D) {
  33949. texture.updateSize(size, size, size);
  33950. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33951. }
  33952. else {
  33953. texture.updateSize(size * size, size);
  33954. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33955. }
  33956. };
  33957. var scene = this.getScene();
  33958. if (scene) {
  33959. scene._loadFile(this.url, callback);
  33960. }
  33961. else {
  33962. this._engine._loadFile(this.url, callback);
  33963. }
  33964. return this._texture;
  33965. };
  33966. /**
  33967. * Starts the loading process of the texture.
  33968. */
  33969. ColorGradingTexture.prototype.loadTexture = function () {
  33970. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33971. this.load3dlTexture();
  33972. }
  33973. };
  33974. /**
  33975. * Clones the color gradind texture.
  33976. */
  33977. ColorGradingTexture.prototype.clone = function () {
  33978. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33979. // Base texture
  33980. newTexture.level = this.level;
  33981. return newTexture;
  33982. };
  33983. /**
  33984. * Called during delayed load for textures.
  33985. */
  33986. ColorGradingTexture.prototype.delayLoad = function () {
  33987. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33988. return;
  33989. }
  33990. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33991. this._texture = this._getFromCache(this.url, true);
  33992. if (!this._texture) {
  33993. this.loadTexture();
  33994. }
  33995. };
  33996. /**
  33997. * Parses a color grading texture serialized by Babylon.
  33998. * @param parsedTexture The texture information being parsedTexture
  33999. * @param scene The scene to load the texture in
  34000. * @param rootUrl The root url of the data assets to load
  34001. * @return A color gradind texture
  34002. */
  34003. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34004. var texture = null;
  34005. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34006. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34007. texture.name = parsedTexture.name;
  34008. texture.level = parsedTexture.level;
  34009. }
  34010. return texture;
  34011. };
  34012. /**
  34013. * Serializes the LUT texture to json format.
  34014. */
  34015. ColorGradingTexture.prototype.serialize = function () {
  34016. if (!this.name) {
  34017. return null;
  34018. }
  34019. var serializationObject = {};
  34020. serializationObject.name = this.name;
  34021. serializationObject.level = this.level;
  34022. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34023. return serializationObject;
  34024. };
  34025. /**
  34026. * Empty line regex stored for GC.
  34027. */
  34028. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34029. return ColorGradingTexture;
  34030. }(BABYLON.BaseTexture));
  34031. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34032. })(BABYLON || (BABYLON = {}));
  34033. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34034. var BABYLON;
  34035. (function (BABYLON) {
  34036. /**
  34037. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34038. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34039. * 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;
  34040. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34041. */
  34042. var ColorCurves = /** @class */ (function () {
  34043. function ColorCurves() {
  34044. this._dirty = true;
  34045. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34046. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34047. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34048. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34049. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34050. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34051. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34052. this._globalHue = 30;
  34053. this._globalDensity = 0;
  34054. this._globalSaturation = 0;
  34055. this._globalExposure = 0;
  34056. this._highlightsHue = 30;
  34057. this._highlightsDensity = 0;
  34058. this._highlightsSaturation = 0;
  34059. this._highlightsExposure = 0;
  34060. this._midtonesHue = 30;
  34061. this._midtonesDensity = 0;
  34062. this._midtonesSaturation = 0;
  34063. this._midtonesExposure = 0;
  34064. this._shadowsHue = 30;
  34065. this._shadowsDensity = 0;
  34066. this._shadowsSaturation = 0;
  34067. this._shadowsExposure = 0;
  34068. }
  34069. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34070. /**
  34071. * Gets the global Hue value.
  34072. * 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).
  34073. */
  34074. get: function () {
  34075. return this._globalHue;
  34076. },
  34077. /**
  34078. * Sets the global Hue value.
  34079. * 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).
  34080. */
  34081. set: function (value) {
  34082. this._globalHue = value;
  34083. this._dirty = true;
  34084. },
  34085. enumerable: true,
  34086. configurable: true
  34087. });
  34088. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34089. /**
  34090. * Gets the global Density value.
  34091. * 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.
  34092. * Values less than zero provide a filter of opposite hue.
  34093. */
  34094. get: function () {
  34095. return this._globalDensity;
  34096. },
  34097. /**
  34098. * Sets the global Density value.
  34099. * 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.
  34100. * Values less than zero provide a filter of opposite hue.
  34101. */
  34102. set: function (value) {
  34103. this._globalDensity = value;
  34104. this._dirty = true;
  34105. },
  34106. enumerable: true,
  34107. configurable: true
  34108. });
  34109. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34110. /**
  34111. * Gets the global Saturation value.
  34112. * 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.
  34113. */
  34114. get: function () {
  34115. return this._globalSaturation;
  34116. },
  34117. /**
  34118. * Sets the global Saturation value.
  34119. * 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.
  34120. */
  34121. set: function (value) {
  34122. this._globalSaturation = value;
  34123. this._dirty = true;
  34124. },
  34125. enumerable: true,
  34126. configurable: true
  34127. });
  34128. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34129. /**
  34130. * Gets the highlights Hue value.
  34131. * 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).
  34132. */
  34133. get: function () {
  34134. return this._highlightsHue;
  34135. },
  34136. /**
  34137. * Sets the highlights Hue value.
  34138. * 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).
  34139. */
  34140. set: function (value) {
  34141. this._highlightsHue = value;
  34142. this._dirty = true;
  34143. },
  34144. enumerable: true,
  34145. configurable: true
  34146. });
  34147. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34148. /**
  34149. * Gets the highlights Density value.
  34150. * 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.
  34151. * Values less than zero provide a filter of opposite hue.
  34152. */
  34153. get: function () {
  34154. return this._highlightsDensity;
  34155. },
  34156. /**
  34157. * Sets the highlights Density value.
  34158. * 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.
  34159. * Values less than zero provide a filter of opposite hue.
  34160. */
  34161. set: function (value) {
  34162. this._highlightsDensity = value;
  34163. this._dirty = true;
  34164. },
  34165. enumerable: true,
  34166. configurable: true
  34167. });
  34168. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34169. /**
  34170. * Gets the highlights Saturation value.
  34171. * 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.
  34172. */
  34173. get: function () {
  34174. return this._highlightsSaturation;
  34175. },
  34176. /**
  34177. * Sets the highlights Saturation value.
  34178. * 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.
  34179. */
  34180. set: function (value) {
  34181. this._highlightsSaturation = value;
  34182. this._dirty = true;
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34188. /**
  34189. * Gets the highlights Exposure value.
  34190. * 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.
  34191. */
  34192. get: function () {
  34193. return this._highlightsExposure;
  34194. },
  34195. /**
  34196. * Sets the highlights Exposure value.
  34197. * 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.
  34198. */
  34199. set: function (value) {
  34200. this._highlightsExposure = value;
  34201. this._dirty = true;
  34202. },
  34203. enumerable: true,
  34204. configurable: true
  34205. });
  34206. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34207. /**
  34208. * Gets the midtones Hue value.
  34209. * 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).
  34210. */
  34211. get: function () {
  34212. return this._midtonesHue;
  34213. },
  34214. /**
  34215. * Sets the midtones Hue value.
  34216. * 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).
  34217. */
  34218. set: function (value) {
  34219. this._midtonesHue = value;
  34220. this._dirty = true;
  34221. },
  34222. enumerable: true,
  34223. configurable: true
  34224. });
  34225. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34226. /**
  34227. * Gets the midtones Density value.
  34228. * 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.
  34229. * Values less than zero provide a filter of opposite hue.
  34230. */
  34231. get: function () {
  34232. return this._midtonesDensity;
  34233. },
  34234. /**
  34235. * Sets the midtones Density value.
  34236. * 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.
  34237. * Values less than zero provide a filter of opposite hue.
  34238. */
  34239. set: function (value) {
  34240. this._midtonesDensity = value;
  34241. this._dirty = true;
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34247. /**
  34248. * Gets the midtones Saturation value.
  34249. * 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.
  34250. */
  34251. get: function () {
  34252. return this._midtonesSaturation;
  34253. },
  34254. /**
  34255. * Sets the midtones Saturation value.
  34256. * 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.
  34257. */
  34258. set: function (value) {
  34259. this._midtonesSaturation = value;
  34260. this._dirty = true;
  34261. },
  34262. enumerable: true,
  34263. configurable: true
  34264. });
  34265. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34266. /**
  34267. * Gets the midtones Exposure value.
  34268. * 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.
  34269. */
  34270. get: function () {
  34271. return this._midtonesExposure;
  34272. },
  34273. /**
  34274. * Sets the midtones Exposure value.
  34275. * 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.
  34276. */
  34277. set: function (value) {
  34278. this._midtonesExposure = value;
  34279. this._dirty = true;
  34280. },
  34281. enumerable: true,
  34282. configurable: true
  34283. });
  34284. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34285. /**
  34286. * Gets the shadows Hue value.
  34287. * 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).
  34288. */
  34289. get: function () {
  34290. return this._shadowsHue;
  34291. },
  34292. /**
  34293. * Sets the shadows Hue value.
  34294. * 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).
  34295. */
  34296. set: function (value) {
  34297. this._shadowsHue = value;
  34298. this._dirty = true;
  34299. },
  34300. enumerable: true,
  34301. configurable: true
  34302. });
  34303. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34304. /**
  34305. * Gets the shadows Density value.
  34306. * 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.
  34307. * Values less than zero provide a filter of opposite hue.
  34308. */
  34309. get: function () {
  34310. return this._shadowsDensity;
  34311. },
  34312. /**
  34313. * Sets the shadows Density value.
  34314. * 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.
  34315. * Values less than zero provide a filter of opposite hue.
  34316. */
  34317. set: function (value) {
  34318. this._shadowsDensity = value;
  34319. this._dirty = true;
  34320. },
  34321. enumerable: true,
  34322. configurable: true
  34323. });
  34324. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34325. /**
  34326. * Gets the shadows Saturation value.
  34327. * 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.
  34328. */
  34329. get: function () {
  34330. return this._shadowsSaturation;
  34331. },
  34332. /**
  34333. * Sets the shadows Saturation value.
  34334. * 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.
  34335. */
  34336. set: function (value) {
  34337. this._shadowsSaturation = value;
  34338. this._dirty = true;
  34339. },
  34340. enumerable: true,
  34341. configurable: true
  34342. });
  34343. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34344. /**
  34345. * Gets the shadows Exposure value.
  34346. * 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.
  34347. */
  34348. get: function () {
  34349. return this._shadowsExposure;
  34350. },
  34351. /**
  34352. * Sets the shadows Exposure value.
  34353. * 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.
  34354. */
  34355. set: function (value) {
  34356. this._shadowsExposure = value;
  34357. this._dirty = true;
  34358. },
  34359. enumerable: true,
  34360. configurable: true
  34361. });
  34362. ColorCurves.prototype.getClassName = function () {
  34363. return "ColorCurves";
  34364. };
  34365. /**
  34366. * Binds the color curves to the shader.
  34367. * @param colorCurves The color curve to bind
  34368. * @param effect The effect to bind to
  34369. */
  34370. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34371. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34372. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34373. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34374. if (colorCurves._dirty) {
  34375. colorCurves._dirty = false;
  34376. // Fill in global info.
  34377. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34378. // Compute highlights info.
  34379. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34380. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34381. // Compute midtones info.
  34382. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34383. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34384. // Compute shadows info.
  34385. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34386. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34387. // Compute deltas (neutral is midtones).
  34388. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34389. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34390. }
  34391. if (effect) {
  34392. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34393. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34394. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34395. }
  34396. };
  34397. /**
  34398. * Prepare the list of uniforms associated with the ColorCurves effects.
  34399. * @param uniformsList The list of uniforms used in the effect
  34400. */
  34401. ColorCurves.PrepareUniforms = function (uniformsList) {
  34402. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34403. };
  34404. /**
  34405. * Returns color grading data based on a hue, density, saturation and exposure value.
  34406. * @param filterHue The hue of the color filter.
  34407. * @param filterDensity The density of the color filter.
  34408. * @param saturation The saturation.
  34409. * @param exposure The exposure.
  34410. * @param result The result data container.
  34411. */
  34412. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34413. if (hue == null) {
  34414. return;
  34415. }
  34416. hue = ColorCurves.clamp(hue, 0, 360);
  34417. density = ColorCurves.clamp(density, -100, 100);
  34418. saturation = ColorCurves.clamp(saturation, -100, 100);
  34419. exposure = ColorCurves.clamp(exposure, -100, 100);
  34420. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34421. // so that the maximum filter density is only 50% control. This provides fine control
  34422. // for small values and reasonable range.
  34423. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34424. density *= 0.5;
  34425. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34426. if (density < 0) {
  34427. density *= -1;
  34428. hue = (hue + 180) % 360;
  34429. }
  34430. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34431. result.scaleToRef(2, result);
  34432. result.a = 1 + 0.01 * saturation;
  34433. };
  34434. /**
  34435. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34436. * @param value The input slider value in range [-100,100].
  34437. * @returns Adjusted value.
  34438. */
  34439. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34440. value /= 100;
  34441. var x = Math.abs(value);
  34442. x = Math.pow(x, 2);
  34443. if (value < 0) {
  34444. x *= -1;
  34445. }
  34446. x *= 100;
  34447. return x;
  34448. };
  34449. /**
  34450. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34451. * @param hue The hue (H) input.
  34452. * @param saturation The saturation (S) input.
  34453. * @param brightness The brightness (B) input.
  34454. * @result An RGBA color represented as Vector4.
  34455. */
  34456. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34457. var h = ColorCurves.clamp(hue, 0, 360);
  34458. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34459. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34460. if (s === 0) {
  34461. result.r = v;
  34462. result.g = v;
  34463. result.b = v;
  34464. }
  34465. else {
  34466. // sector 0 to 5
  34467. h /= 60;
  34468. var i = Math.floor(h);
  34469. // fractional part of h
  34470. var f = h - i;
  34471. var p = v * (1 - s);
  34472. var q = v * (1 - s * f);
  34473. var t = v * (1 - s * (1 - f));
  34474. switch (i) {
  34475. case 0:
  34476. result.r = v;
  34477. result.g = t;
  34478. result.b = p;
  34479. break;
  34480. case 1:
  34481. result.r = q;
  34482. result.g = v;
  34483. result.b = p;
  34484. break;
  34485. case 2:
  34486. result.r = p;
  34487. result.g = v;
  34488. result.b = t;
  34489. break;
  34490. case 3:
  34491. result.r = p;
  34492. result.g = q;
  34493. result.b = v;
  34494. break;
  34495. case 4:
  34496. result.r = t;
  34497. result.g = p;
  34498. result.b = v;
  34499. break;
  34500. default:// case 5:
  34501. result.r = v;
  34502. result.g = p;
  34503. result.b = q;
  34504. break;
  34505. }
  34506. }
  34507. result.a = 1;
  34508. };
  34509. /**
  34510. * Returns a value clamped between min and max
  34511. * @param value The value to clamp
  34512. * @param min The minimum of value
  34513. * @param max The maximum of value
  34514. * @returns The clamped value.
  34515. */
  34516. ColorCurves.clamp = function (value, min, max) {
  34517. return Math.min(Math.max(value, min), max);
  34518. };
  34519. /**
  34520. * Clones the current color curve instance.
  34521. * @return The cloned curves
  34522. */
  34523. ColorCurves.prototype.clone = function () {
  34524. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34525. };
  34526. /**
  34527. * Serializes the current color curve instance to a json representation.
  34528. * @return a JSON representation
  34529. */
  34530. ColorCurves.prototype.serialize = function () {
  34531. return BABYLON.SerializationHelper.Serialize(this);
  34532. };
  34533. /**
  34534. * Parses the color curve from a json representation.
  34535. * @param source the JSON source to parse
  34536. * @return The parsed curves
  34537. */
  34538. ColorCurves.Parse = function (source) {
  34539. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34540. };
  34541. __decorate([
  34542. BABYLON.serialize()
  34543. ], ColorCurves.prototype, "_globalHue", void 0);
  34544. __decorate([
  34545. BABYLON.serialize()
  34546. ], ColorCurves.prototype, "_globalDensity", void 0);
  34547. __decorate([
  34548. BABYLON.serialize()
  34549. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34550. __decorate([
  34551. BABYLON.serialize()
  34552. ], ColorCurves.prototype, "_globalExposure", void 0);
  34553. __decorate([
  34554. BABYLON.serialize()
  34555. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34556. __decorate([
  34557. BABYLON.serialize()
  34558. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34559. __decorate([
  34560. BABYLON.serialize()
  34561. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34562. __decorate([
  34563. BABYLON.serialize()
  34564. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34565. __decorate([
  34566. BABYLON.serialize()
  34567. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34568. __decorate([
  34569. BABYLON.serialize()
  34570. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34571. __decorate([
  34572. BABYLON.serialize()
  34573. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34574. __decorate([
  34575. BABYLON.serialize()
  34576. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34577. return ColorCurves;
  34578. }());
  34579. BABYLON.ColorCurves = ColorCurves;
  34580. })(BABYLON || (BABYLON = {}));
  34581. //# sourceMappingURL=babylon.colorCurves.js.map
  34582. //# sourceMappingURL=babylon.behavior.js.map
  34583. var BABYLON;
  34584. (function (BABYLON) {
  34585. var MaterialHelper = /** @class */ (function () {
  34586. function MaterialHelper() {
  34587. }
  34588. MaterialHelper.BindEyePosition = function (effect, scene) {
  34589. if (scene._forcedViewPosition) {
  34590. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34591. return;
  34592. }
  34593. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34594. };
  34595. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34596. defines._needUVs = true;
  34597. defines[key] = true;
  34598. if (texture.getTextureMatrix().isIdentity(true)) {
  34599. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34600. if (texture.coordinatesIndex === 0) {
  34601. defines["MAINUV1"] = true;
  34602. }
  34603. else {
  34604. defines["MAINUV2"] = true;
  34605. }
  34606. }
  34607. else {
  34608. defines[key + "DIRECTUV"] = 0;
  34609. }
  34610. };
  34611. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34612. var matrix = texture.getTextureMatrix();
  34613. if (!matrix.isIdentity(true)) {
  34614. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34615. }
  34616. };
  34617. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34618. if (defines._areMiscDirty) {
  34619. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34620. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34621. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34622. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34623. }
  34624. };
  34625. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34626. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34627. var changed = false;
  34628. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34629. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34630. changed = true;
  34631. }
  34632. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34633. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34634. changed = true;
  34635. }
  34636. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34637. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34638. changed = true;
  34639. }
  34640. if (defines["INSTANCES"] !== useInstances) {
  34641. defines["INSTANCES"] = useInstances;
  34642. changed = true;
  34643. }
  34644. if (changed) {
  34645. defines.markAsUnprocessed();
  34646. }
  34647. };
  34648. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34649. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34650. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34651. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34652. return false;
  34653. }
  34654. defines._normals = defines._needNormals;
  34655. defines._uvs = defines._needUVs;
  34656. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34657. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34658. defines["TANGENT"] = true;
  34659. }
  34660. if (defines._needUVs) {
  34661. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34662. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34663. }
  34664. else {
  34665. defines["UV1"] = false;
  34666. defines["UV2"] = false;
  34667. }
  34668. if (useVertexColor) {
  34669. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34670. defines["VERTEXCOLOR"] = hasVertexColors;
  34671. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34672. }
  34673. if (useBones) {
  34674. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34675. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34676. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34677. }
  34678. else {
  34679. defines["NUM_BONE_INFLUENCERS"] = 0;
  34680. defines["BonesPerMesh"] = 0;
  34681. }
  34682. }
  34683. if (useMorphTargets) {
  34684. var manager = mesh.morphTargetManager;
  34685. if (manager) {
  34686. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34687. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34688. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34689. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34690. }
  34691. else {
  34692. defines["MORPHTARGETS_TANGENT"] = false;
  34693. defines["MORPHTARGETS_NORMAL"] = false;
  34694. defines["MORPHTARGETS"] = false;
  34695. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34696. }
  34697. }
  34698. return true;
  34699. };
  34700. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34701. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34702. if (disableLighting === void 0) { disableLighting = false; }
  34703. if (!defines._areLightsDirty) {
  34704. return defines._needNormals;
  34705. }
  34706. var lightIndex = 0;
  34707. var needNormals = false;
  34708. var needRebuild = false;
  34709. var lightmapMode = false;
  34710. var shadowEnabled = false;
  34711. var specularEnabled = false;
  34712. if (scene.lightsEnabled && !disableLighting) {
  34713. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34714. var light = _a[_i];
  34715. needNormals = true;
  34716. if (defines["LIGHT" + lightIndex] === undefined) {
  34717. needRebuild = true;
  34718. }
  34719. defines["LIGHT" + lightIndex] = true;
  34720. defines["SPOTLIGHT" + lightIndex] = false;
  34721. defines["HEMILIGHT" + lightIndex] = false;
  34722. defines["POINTLIGHT" + lightIndex] = false;
  34723. defines["DIRLIGHT" + lightIndex] = false;
  34724. var type;
  34725. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34726. type = "SPOTLIGHT" + lightIndex;
  34727. }
  34728. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34729. type = "HEMILIGHT" + lightIndex;
  34730. }
  34731. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34732. type = "POINTLIGHT" + lightIndex;
  34733. }
  34734. else {
  34735. type = "DIRLIGHT" + lightIndex;
  34736. }
  34737. defines[type] = true;
  34738. // Specular
  34739. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34740. specularEnabled = true;
  34741. }
  34742. // Shadows
  34743. defines["SHADOW" + lightIndex] = false;
  34744. defines["SHADOWPCF" + lightIndex] = false;
  34745. defines["SHADOWESM" + lightIndex] = false;
  34746. defines["SHADOWCUBE" + lightIndex] = false;
  34747. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34748. var shadowGenerator = light.getShadowGenerator();
  34749. if (shadowGenerator) {
  34750. shadowEnabled = true;
  34751. shadowGenerator.prepareDefines(defines, lightIndex);
  34752. }
  34753. }
  34754. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34755. lightmapMode = true;
  34756. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34757. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34758. }
  34759. else {
  34760. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34761. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34762. }
  34763. lightIndex++;
  34764. if (lightIndex === maxSimultaneousLights)
  34765. break;
  34766. }
  34767. }
  34768. defines["SPECULARTERM"] = specularEnabled;
  34769. defines["SHADOWS"] = shadowEnabled;
  34770. // Resetting all other lights if any
  34771. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34772. if (defines["LIGHT" + index] !== undefined) {
  34773. defines["LIGHT" + index] = false;
  34774. defines["HEMILIGHT" + lightIndex] = false;
  34775. defines["POINTLIGHT" + lightIndex] = false;
  34776. defines["DIRLIGHT" + lightIndex] = false;
  34777. defines["SPOTLIGHT" + lightIndex] = false;
  34778. defines["SHADOW" + lightIndex] = false;
  34779. }
  34780. }
  34781. var caps = scene.getEngine().getCaps();
  34782. if (defines["SHADOWFLOAT"] === undefined) {
  34783. needRebuild = true;
  34784. }
  34785. defines["SHADOWFLOAT"] = shadowEnabled &&
  34786. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34787. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34788. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34789. if (needRebuild) {
  34790. defines.rebuild();
  34791. }
  34792. return needNormals;
  34793. };
  34794. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34795. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34796. var uniformsList;
  34797. var uniformBuffersList = null;
  34798. if (uniformsListOrOptions.uniformsNames) {
  34799. var options = uniformsListOrOptions;
  34800. uniformsList = options.uniformsNames;
  34801. uniformBuffersList = options.uniformBuffersNames;
  34802. samplersList = options.samplers;
  34803. defines = options.defines;
  34804. maxSimultaneousLights = options.maxSimultaneousLights;
  34805. }
  34806. else {
  34807. uniformsList = uniformsListOrOptions;
  34808. if (!samplersList) {
  34809. samplersList = [];
  34810. }
  34811. }
  34812. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34813. if (!defines["LIGHT" + lightIndex]) {
  34814. break;
  34815. }
  34816. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34817. if (uniformBuffersList) {
  34818. uniformBuffersList.push("Light" + lightIndex);
  34819. }
  34820. samplersList.push("shadowSampler" + lightIndex);
  34821. }
  34822. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34823. uniformsList.push("morphTargetInfluences");
  34824. }
  34825. };
  34826. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34827. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34828. if (rank === void 0) { rank = 0; }
  34829. var lightFallbackRank = 0;
  34830. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34831. if (!defines["LIGHT" + lightIndex]) {
  34832. break;
  34833. }
  34834. if (lightIndex > 0) {
  34835. lightFallbackRank = rank + lightIndex;
  34836. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34837. }
  34838. if (!defines["SHADOWS"]) {
  34839. if (defines["SHADOW" + lightIndex]) {
  34840. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34841. }
  34842. if (defines["SHADOWPCF" + lightIndex]) {
  34843. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34844. }
  34845. if (defines["SHADOWESM" + lightIndex]) {
  34846. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34847. }
  34848. }
  34849. }
  34850. return lightFallbackRank++;
  34851. };
  34852. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34853. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34854. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34855. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34856. var manager = mesh.morphTargetManager;
  34857. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34858. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34859. for (var index = 0; index < influencers; index++) {
  34860. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34861. if (normal) {
  34862. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34863. }
  34864. if (tangent) {
  34865. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34866. }
  34867. if (attribs.length > maxAttributesCount) {
  34868. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34869. }
  34870. }
  34871. }
  34872. };
  34873. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34874. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34875. fallbacks.addCPUSkinningFallback(0, mesh);
  34876. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34877. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34878. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34879. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34880. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34881. }
  34882. }
  34883. };
  34884. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34885. if (defines["INSTANCES"]) {
  34886. attribs.push("world0");
  34887. attribs.push("world1");
  34888. attribs.push("world2");
  34889. attribs.push("world3");
  34890. }
  34891. };
  34892. // Bindings
  34893. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34894. if (light.shadowEnabled && mesh.receiveShadows) {
  34895. var shadowGenerator = light.getShadowGenerator();
  34896. if (shadowGenerator) {
  34897. shadowGenerator.bindShadowLight(lightIndex, effect);
  34898. }
  34899. }
  34900. };
  34901. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34902. light.transferToEffect(effect, lightIndex + "");
  34903. };
  34904. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34905. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34906. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34907. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34908. for (var i = 0; i < len; i++) {
  34909. var light = mesh._lightSources[i];
  34910. var iAsString = i.toString();
  34911. var scaledIntensity = light.getScaledIntensity();
  34912. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34913. MaterialHelper.BindLightProperties(light, effect, i);
  34914. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34915. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34916. if (defines["SPECULARTERM"]) {
  34917. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34918. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34919. }
  34920. // Shadows
  34921. if (scene.shadowsEnabled) {
  34922. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34923. }
  34924. light._uniformBuffer.update();
  34925. }
  34926. };
  34927. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34928. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34929. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34930. effect.setColor3("vFogColor", scene.fogColor);
  34931. }
  34932. };
  34933. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34934. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34935. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34936. if (matrices && effect) {
  34937. effect.setMatrices("mBones", matrices);
  34938. }
  34939. }
  34940. };
  34941. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34942. var manager = abstractMesh.morphTargetManager;
  34943. if (!abstractMesh || !manager) {
  34944. return;
  34945. }
  34946. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34947. };
  34948. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34949. if (defines["LOGARITHMICDEPTH"]) {
  34950. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34951. }
  34952. };
  34953. MaterialHelper.BindClipPlane = function (effect, scene) {
  34954. if (scene.clipPlane) {
  34955. var clipPlane = scene.clipPlane;
  34956. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34957. }
  34958. };
  34959. return MaterialHelper;
  34960. }());
  34961. BABYLON.MaterialHelper = MaterialHelper;
  34962. })(BABYLON || (BABYLON = {}));
  34963. //# sourceMappingURL=babylon.materialHelper.js.map
  34964. var BABYLON;
  34965. (function (BABYLON) {
  34966. var PushMaterial = /** @class */ (function (_super) {
  34967. __extends(PushMaterial, _super);
  34968. function PushMaterial(name, scene) {
  34969. var _this = _super.call(this, name, scene) || this;
  34970. _this.storeEffectOnSubMeshes = true;
  34971. return _this;
  34972. }
  34973. PushMaterial.prototype.getEffect = function () {
  34974. return this._activeEffect;
  34975. };
  34976. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34977. if (!mesh) {
  34978. return false;
  34979. }
  34980. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34981. return true;
  34982. }
  34983. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34984. };
  34985. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34986. this._activeEffect.setMatrix("world", world);
  34987. };
  34988. PushMaterial.prototype.bind = function (world, mesh) {
  34989. if (!mesh) {
  34990. return;
  34991. }
  34992. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34993. };
  34994. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34995. if (effect === void 0) { effect = null; }
  34996. _super.prototype._afterBind.call(this, mesh);
  34997. this.getScene()._cachedEffect = effect;
  34998. };
  34999. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35000. if (visibility === void 0) { visibility = 1; }
  35001. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35002. };
  35003. return PushMaterial;
  35004. }(BABYLON.Material));
  35005. BABYLON.PushMaterial = PushMaterial;
  35006. })(BABYLON || (BABYLON = {}));
  35007. //# sourceMappingURL=babylon.pushMaterial.js.map
  35008. var BABYLON;
  35009. (function (BABYLON) {
  35010. var StandardMaterialDefines = /** @class */ (function (_super) {
  35011. __extends(StandardMaterialDefines, _super);
  35012. function StandardMaterialDefines() {
  35013. var _this = _super.call(this) || this;
  35014. _this.MAINUV1 = false;
  35015. _this.MAINUV2 = false;
  35016. _this.DIFFUSE = false;
  35017. _this.DIFFUSEDIRECTUV = 0;
  35018. _this.AMBIENT = false;
  35019. _this.AMBIENTDIRECTUV = 0;
  35020. _this.OPACITY = false;
  35021. _this.OPACITYDIRECTUV = 0;
  35022. _this.OPACITYRGB = false;
  35023. _this.REFLECTION = false;
  35024. _this.EMISSIVE = false;
  35025. _this.EMISSIVEDIRECTUV = 0;
  35026. _this.SPECULAR = false;
  35027. _this.SPECULARDIRECTUV = 0;
  35028. _this.BUMP = false;
  35029. _this.BUMPDIRECTUV = 0;
  35030. _this.PARALLAX = false;
  35031. _this.PARALLAXOCCLUSION = false;
  35032. _this.SPECULAROVERALPHA = false;
  35033. _this.CLIPPLANE = false;
  35034. _this.ALPHATEST = false;
  35035. _this.DEPTHPREPASS = false;
  35036. _this.ALPHAFROMDIFFUSE = false;
  35037. _this.POINTSIZE = false;
  35038. _this.FOG = false;
  35039. _this.SPECULARTERM = false;
  35040. _this.DIFFUSEFRESNEL = false;
  35041. _this.OPACITYFRESNEL = false;
  35042. _this.REFLECTIONFRESNEL = false;
  35043. _this.REFRACTIONFRESNEL = false;
  35044. _this.EMISSIVEFRESNEL = false;
  35045. _this.FRESNEL = false;
  35046. _this.NORMAL = false;
  35047. _this.UV1 = false;
  35048. _this.UV2 = false;
  35049. _this.VERTEXCOLOR = false;
  35050. _this.VERTEXALPHA = false;
  35051. _this.NUM_BONE_INFLUENCERS = 0;
  35052. _this.BonesPerMesh = 0;
  35053. _this.INSTANCES = false;
  35054. _this.GLOSSINESS = false;
  35055. _this.ROUGHNESS = false;
  35056. _this.EMISSIVEASILLUMINATION = false;
  35057. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35058. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35059. _this.LIGHTMAP = false;
  35060. _this.LIGHTMAPDIRECTUV = 0;
  35061. _this.USELIGHTMAPASSHADOWMAP = false;
  35062. _this.REFLECTIONMAP_3D = false;
  35063. _this.REFLECTIONMAP_SPHERICAL = false;
  35064. _this.REFLECTIONMAP_PLANAR = false;
  35065. _this.REFLECTIONMAP_CUBIC = false;
  35066. _this.REFLECTIONMAP_PROJECTION = false;
  35067. _this.REFLECTIONMAP_SKYBOX = false;
  35068. _this.REFLECTIONMAP_EXPLICIT = false;
  35069. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35070. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35071. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35072. _this.INVERTCUBICMAP = false;
  35073. _this.LOGARITHMICDEPTH = false;
  35074. _this.REFRACTION = false;
  35075. _this.REFRACTIONMAP_3D = false;
  35076. _this.REFLECTIONOVERALPHA = false;
  35077. _this.TWOSIDEDLIGHTING = false;
  35078. _this.SHADOWFLOAT = false;
  35079. _this.MORPHTARGETS = false;
  35080. _this.MORPHTARGETS_NORMAL = false;
  35081. _this.MORPHTARGETS_TANGENT = false;
  35082. _this.NUM_MORPH_INFLUENCERS = 0;
  35083. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35084. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35085. _this.IMAGEPROCESSING = false;
  35086. _this.VIGNETTE = false;
  35087. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35088. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35089. _this.TONEMAPPING = false;
  35090. _this.CONTRAST = false;
  35091. _this.COLORCURVES = false;
  35092. _this.COLORGRADING = false;
  35093. _this.COLORGRADING3D = false;
  35094. _this.SAMPLER3DGREENDEPTH = false;
  35095. _this.SAMPLER3DBGRMAP = false;
  35096. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35097. _this.EXPOSURE = false;
  35098. _this.rebuild();
  35099. return _this;
  35100. }
  35101. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35102. var modes = [
  35103. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35104. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35105. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35106. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35107. ];
  35108. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35109. var mode = modes_1[_i];
  35110. this[mode] = (mode === modeToEnable);
  35111. }
  35112. };
  35113. return StandardMaterialDefines;
  35114. }(BABYLON.MaterialDefines));
  35115. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35116. var StandardMaterial = /** @class */ (function (_super) {
  35117. __extends(StandardMaterial, _super);
  35118. function StandardMaterial(name, scene) {
  35119. var _this = _super.call(this, name, scene) || this;
  35120. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35121. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35122. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35123. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35124. _this.specularPower = 64;
  35125. _this._useAlphaFromDiffuseTexture = false;
  35126. _this._useEmissiveAsIllumination = false;
  35127. _this._linkEmissiveWithDiffuse = false;
  35128. _this._useSpecularOverAlpha = false;
  35129. _this._useReflectionOverAlpha = false;
  35130. _this._disableLighting = false;
  35131. _this._useParallax = false;
  35132. _this._useParallaxOcclusion = false;
  35133. _this.parallaxScaleBias = 0.05;
  35134. _this._roughness = 0;
  35135. _this.indexOfRefraction = 0.98;
  35136. _this.invertRefractionY = true;
  35137. _this._useLightmapAsShadowmap = false;
  35138. _this._useReflectionFresnelFromSpecular = false;
  35139. _this._useGlossinessFromSpecularMapAlpha = false;
  35140. _this._maxSimultaneousLights = 4;
  35141. /**
  35142. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35143. */
  35144. _this._invertNormalMapX = false;
  35145. /**
  35146. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35147. */
  35148. _this._invertNormalMapY = false;
  35149. /**
  35150. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35151. */
  35152. _this._twoSidedLighting = false;
  35153. _this._renderTargets = new BABYLON.SmartArray(16);
  35154. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35155. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35156. // Setup the default processing configuration to the scene.
  35157. _this._attachImageProcessingConfiguration(null);
  35158. _this.getRenderTargetTextures = function () {
  35159. _this._renderTargets.reset();
  35160. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35161. _this._renderTargets.push(_this._reflectionTexture);
  35162. }
  35163. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35164. _this._renderTargets.push(_this._refractionTexture);
  35165. }
  35166. return _this._renderTargets;
  35167. };
  35168. return _this;
  35169. }
  35170. ;
  35171. ;
  35172. ;
  35173. ;
  35174. ;
  35175. ;
  35176. ;
  35177. ;
  35178. ;
  35179. ;
  35180. ;
  35181. ;
  35182. ;
  35183. ;
  35184. ;
  35185. ;
  35186. ;
  35187. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35188. /**
  35189. * Gets the image processing configuration used either in this material.
  35190. */
  35191. get: function () {
  35192. return this._imageProcessingConfiguration;
  35193. },
  35194. /**
  35195. * Sets the Default image processing configuration used either in the this material.
  35196. *
  35197. * If sets to null, the scene one is in use.
  35198. */
  35199. set: function (value) {
  35200. this._attachImageProcessingConfiguration(value);
  35201. // Ensure the effect will be rebuilt.
  35202. this._markAllSubMeshesAsTexturesDirty();
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. /**
  35208. * Attaches a new image processing configuration to the Standard Material.
  35209. * @param configuration
  35210. */
  35211. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35212. var _this = this;
  35213. if (configuration === this._imageProcessingConfiguration) {
  35214. return;
  35215. }
  35216. // Detaches observer.
  35217. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35218. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35219. }
  35220. // Pick the scene configuration if needed.
  35221. if (!configuration) {
  35222. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35223. }
  35224. else {
  35225. this._imageProcessingConfiguration = configuration;
  35226. }
  35227. // Attaches observer.
  35228. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35229. _this._markAllSubMeshesAsImageProcessingDirty();
  35230. });
  35231. };
  35232. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35233. /**
  35234. * Gets wether the color curves effect is enabled.
  35235. */
  35236. get: function () {
  35237. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35238. },
  35239. /**
  35240. * Sets wether the color curves effect is enabled.
  35241. */
  35242. set: function (value) {
  35243. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35249. /**
  35250. * Gets wether the color grading effect is enabled.
  35251. */
  35252. get: function () {
  35253. return this.imageProcessingConfiguration.colorGradingEnabled;
  35254. },
  35255. /**
  35256. * Gets wether the color grading effect is enabled.
  35257. */
  35258. set: function (value) {
  35259. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35260. },
  35261. enumerable: true,
  35262. configurable: true
  35263. });
  35264. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35265. /**
  35266. * Gets wether tonemapping is enabled or not.
  35267. */
  35268. get: function () {
  35269. return this._imageProcessingConfiguration.toneMappingEnabled;
  35270. },
  35271. /**
  35272. * Sets wether tonemapping is enabled or not
  35273. */
  35274. set: function (value) {
  35275. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. ;
  35281. ;
  35282. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35283. /**
  35284. * The camera exposure used on this material.
  35285. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35286. * This corresponds to a photographic exposure.
  35287. */
  35288. get: function () {
  35289. return this._imageProcessingConfiguration.exposure;
  35290. },
  35291. /**
  35292. * The camera exposure used on this material.
  35293. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35294. * This corresponds to a photographic exposure.
  35295. */
  35296. set: function (value) {
  35297. this._imageProcessingConfiguration.exposure = value;
  35298. },
  35299. enumerable: true,
  35300. configurable: true
  35301. });
  35302. ;
  35303. ;
  35304. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35305. /**
  35306. * Gets The camera contrast used on this material.
  35307. */
  35308. get: function () {
  35309. return this._imageProcessingConfiguration.contrast;
  35310. },
  35311. /**
  35312. * Sets The camera contrast used on this material.
  35313. */
  35314. set: function (value) {
  35315. this._imageProcessingConfiguration.contrast = value;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35321. /**
  35322. * Gets the Color Grading 2D Lookup Texture.
  35323. */
  35324. get: function () {
  35325. return this._imageProcessingConfiguration.colorGradingTexture;
  35326. },
  35327. /**
  35328. * Sets the Color Grading 2D Lookup Texture.
  35329. */
  35330. set: function (value) {
  35331. this._imageProcessingConfiguration.colorGradingTexture = value;
  35332. },
  35333. enumerable: true,
  35334. configurable: true
  35335. });
  35336. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35337. /**
  35338. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35339. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35340. * 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;
  35341. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35342. */
  35343. get: function () {
  35344. return this._imageProcessingConfiguration.colorCurves;
  35345. },
  35346. /**
  35347. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35348. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35349. * 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;
  35350. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35351. */
  35352. set: function (value) {
  35353. this._imageProcessingConfiguration.colorCurves = value;
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. StandardMaterial.prototype.getClassName = function () {
  35359. return "StandardMaterial";
  35360. };
  35361. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35362. get: function () {
  35363. return this._useLogarithmicDepth;
  35364. },
  35365. set: function (value) {
  35366. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35367. this._markAllSubMeshesAsMiscDirty();
  35368. },
  35369. enumerable: true,
  35370. configurable: true
  35371. });
  35372. StandardMaterial.prototype.needAlphaBlending = function () {
  35373. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35374. };
  35375. StandardMaterial.prototype.needAlphaTesting = function () {
  35376. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35377. };
  35378. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35379. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35380. };
  35381. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35382. return this._diffuseTexture;
  35383. };
  35384. /**
  35385. * Child classes can use it to update shaders
  35386. */
  35387. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35388. if (useInstances === void 0) { useInstances = false; }
  35389. if (subMesh.effect && this.isFrozen) {
  35390. if (this._wasPreviouslyReady && subMesh.effect) {
  35391. return true;
  35392. }
  35393. }
  35394. if (!subMesh._materialDefines) {
  35395. subMesh._materialDefines = new StandardMaterialDefines();
  35396. }
  35397. var scene = this.getScene();
  35398. var defines = subMesh._materialDefines;
  35399. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35400. if (defines._renderId === scene.getRenderId()) {
  35401. return true;
  35402. }
  35403. }
  35404. var engine = scene.getEngine();
  35405. // Lights
  35406. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35407. // Textures
  35408. if (defines._areTexturesDirty) {
  35409. defines._needUVs = false;
  35410. defines.MAINUV1 = false;
  35411. defines.MAINUV2 = false;
  35412. if (scene.texturesEnabled) {
  35413. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35414. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35415. return false;
  35416. }
  35417. else {
  35418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35419. }
  35420. }
  35421. else {
  35422. defines.DIFFUSE = false;
  35423. }
  35424. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35425. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35426. return false;
  35427. }
  35428. else {
  35429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35430. }
  35431. }
  35432. else {
  35433. defines.AMBIENT = false;
  35434. }
  35435. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35436. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35437. return false;
  35438. }
  35439. else {
  35440. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35441. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35442. }
  35443. }
  35444. else {
  35445. defines.OPACITY = false;
  35446. }
  35447. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35448. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35449. return false;
  35450. }
  35451. else {
  35452. defines._needNormals = true;
  35453. defines.REFLECTION = true;
  35454. defines.ROUGHNESS = (this._roughness > 0);
  35455. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35456. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35457. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35458. switch (this._reflectionTexture.coordinatesMode) {
  35459. case BABYLON.Texture.CUBIC_MODE:
  35460. case BABYLON.Texture.INVCUBIC_MODE:
  35461. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35462. break;
  35463. case BABYLON.Texture.EXPLICIT_MODE:
  35464. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35465. break;
  35466. case BABYLON.Texture.PLANAR_MODE:
  35467. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35468. break;
  35469. case BABYLON.Texture.PROJECTION_MODE:
  35470. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35471. break;
  35472. case BABYLON.Texture.SKYBOX_MODE:
  35473. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35474. break;
  35475. case BABYLON.Texture.SPHERICAL_MODE:
  35476. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35477. break;
  35478. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35479. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35480. break;
  35481. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35482. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35483. break;
  35484. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35485. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35486. break;
  35487. }
  35488. }
  35489. }
  35490. else {
  35491. defines.REFLECTION = false;
  35492. }
  35493. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35494. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35495. return false;
  35496. }
  35497. else {
  35498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35499. }
  35500. }
  35501. else {
  35502. defines.EMISSIVE = false;
  35503. }
  35504. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35505. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35506. return false;
  35507. }
  35508. else {
  35509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35510. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35511. }
  35512. }
  35513. else {
  35514. defines.LIGHTMAP = false;
  35515. }
  35516. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35517. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35518. return false;
  35519. }
  35520. else {
  35521. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35522. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35523. }
  35524. }
  35525. else {
  35526. defines.SPECULAR = false;
  35527. }
  35528. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35529. // Bump texure can not be not blocking.
  35530. if (!this._bumpTexture.isReady()) {
  35531. return false;
  35532. }
  35533. else {
  35534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35535. defines.PARALLAX = this._useParallax;
  35536. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35537. }
  35538. }
  35539. else {
  35540. defines.BUMP = false;
  35541. }
  35542. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35543. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35544. return false;
  35545. }
  35546. else {
  35547. defines._needUVs = true;
  35548. defines.REFRACTION = true;
  35549. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35550. }
  35551. }
  35552. else {
  35553. defines.REFRACTION = false;
  35554. }
  35555. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35556. }
  35557. else {
  35558. defines.DIFFUSE = false;
  35559. defines.AMBIENT = false;
  35560. defines.OPACITY = false;
  35561. defines.REFLECTION = false;
  35562. defines.EMISSIVE = false;
  35563. defines.LIGHTMAP = false;
  35564. defines.BUMP = false;
  35565. defines.REFRACTION = false;
  35566. }
  35567. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35568. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35569. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35570. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35571. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35572. }
  35573. if (defines._areImageProcessingDirty) {
  35574. if (!this._imageProcessingConfiguration.isReady()) {
  35575. return false;
  35576. }
  35577. this._imageProcessingConfiguration.prepareDefines(defines);
  35578. }
  35579. if (defines._areFresnelDirty) {
  35580. if (StandardMaterial.FresnelEnabled) {
  35581. // Fresnel
  35582. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35583. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35584. this._reflectionFresnelParameters) {
  35585. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35586. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35587. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35588. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35589. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35590. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35591. defines._needNormals = true;
  35592. defines.FRESNEL = true;
  35593. }
  35594. }
  35595. else {
  35596. defines.FRESNEL = false;
  35597. }
  35598. }
  35599. // Misc.
  35600. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35601. // Attribs
  35602. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35603. // Values that need to be evaluated on every frame
  35604. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35605. // Get correct effect
  35606. if (defines.isDirty) {
  35607. defines.markAsProcessed();
  35608. scene.resetCachedMaterial();
  35609. // Fallbacks
  35610. var fallbacks = new BABYLON.EffectFallbacks();
  35611. if (defines.REFLECTION) {
  35612. fallbacks.addFallback(0, "REFLECTION");
  35613. }
  35614. if (defines.SPECULAR) {
  35615. fallbacks.addFallback(0, "SPECULAR");
  35616. }
  35617. if (defines.BUMP) {
  35618. fallbacks.addFallback(0, "BUMP");
  35619. }
  35620. if (defines.PARALLAX) {
  35621. fallbacks.addFallback(1, "PARALLAX");
  35622. }
  35623. if (defines.PARALLAXOCCLUSION) {
  35624. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35625. }
  35626. if (defines.SPECULAROVERALPHA) {
  35627. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35628. }
  35629. if (defines.FOG) {
  35630. fallbacks.addFallback(1, "FOG");
  35631. }
  35632. if (defines.POINTSIZE) {
  35633. fallbacks.addFallback(0, "POINTSIZE");
  35634. }
  35635. if (defines.LOGARITHMICDEPTH) {
  35636. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35637. }
  35638. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35639. if (defines.SPECULARTERM) {
  35640. fallbacks.addFallback(0, "SPECULARTERM");
  35641. }
  35642. if (defines.DIFFUSEFRESNEL) {
  35643. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35644. }
  35645. if (defines.OPACITYFRESNEL) {
  35646. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35647. }
  35648. if (defines.REFLECTIONFRESNEL) {
  35649. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35650. }
  35651. if (defines.EMISSIVEFRESNEL) {
  35652. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35653. }
  35654. if (defines.FRESNEL) {
  35655. fallbacks.addFallback(4, "FRESNEL");
  35656. }
  35657. //Attributes
  35658. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35659. if (defines.NORMAL) {
  35660. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35661. }
  35662. if (defines.UV1) {
  35663. attribs.push(BABYLON.VertexBuffer.UVKind);
  35664. }
  35665. if (defines.UV2) {
  35666. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35667. }
  35668. if (defines.VERTEXCOLOR) {
  35669. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35670. }
  35671. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35672. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35673. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35674. var shaderName = "default";
  35675. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35676. "vFogInfos", "vFogColor", "pointSize",
  35677. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35678. "mBones",
  35679. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35680. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35681. "logarithmicDepthConstant", "vTangentSpaceParams"
  35682. ];
  35683. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35684. var uniformBuffers = ["Material", "Scene"];
  35685. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35686. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35687. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35688. uniformsNames: uniforms,
  35689. uniformBuffersNames: uniformBuffers,
  35690. samplers: samplers,
  35691. defines: defines,
  35692. maxSimultaneousLights: this._maxSimultaneousLights
  35693. });
  35694. if (this.customShaderNameResolve) {
  35695. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35696. }
  35697. var join = defines.toString();
  35698. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35699. attributes: attribs,
  35700. uniformsNames: uniforms,
  35701. uniformBuffersNames: uniformBuffers,
  35702. samplers: samplers,
  35703. defines: join,
  35704. fallbacks: fallbacks,
  35705. onCompiled: this.onCompiled,
  35706. onError: this.onError,
  35707. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35708. }, engine), defines);
  35709. this.buildUniformLayout();
  35710. }
  35711. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35712. return false;
  35713. }
  35714. defines._renderId = scene.getRenderId();
  35715. this._wasPreviouslyReady = true;
  35716. return true;
  35717. };
  35718. StandardMaterial.prototype.buildUniformLayout = function () {
  35719. // Order is important !
  35720. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35721. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35722. this._uniformBuffer.addUniform("opacityParts", 4);
  35723. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35724. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35725. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35726. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35727. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35728. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35729. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35730. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35731. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35732. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35733. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35734. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35735. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35736. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35737. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35738. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35739. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35740. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35741. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35742. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35743. this._uniformBuffer.addUniform("specularMatrix", 16);
  35744. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35745. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35746. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35747. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35748. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35749. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35750. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35751. this._uniformBuffer.addUniform("pointSize", 1);
  35752. this._uniformBuffer.create();
  35753. };
  35754. StandardMaterial.prototype.unbind = function () {
  35755. if (this._activeEffect) {
  35756. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35757. this._activeEffect.setTexture("reflection2DSampler", null);
  35758. }
  35759. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35760. this._activeEffect.setTexture("refraction2DSampler", null);
  35761. }
  35762. }
  35763. _super.prototype.unbind.call(this);
  35764. };
  35765. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35766. var scene = this.getScene();
  35767. var defines = subMesh._materialDefines;
  35768. if (!defines) {
  35769. return;
  35770. }
  35771. var effect = subMesh.effect;
  35772. if (!effect) {
  35773. return;
  35774. }
  35775. this._activeEffect = effect;
  35776. // Matrices
  35777. this.bindOnlyWorldMatrix(world);
  35778. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35779. // Bones
  35780. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35781. if (mustRebind) {
  35782. this._uniformBuffer.bindToEffect(effect, "Material");
  35783. this.bindViewProjection(effect);
  35784. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35785. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35786. // Fresnel
  35787. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35788. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35789. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35790. }
  35791. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35792. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35793. }
  35794. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35795. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35796. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35797. }
  35798. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35799. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35800. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35801. }
  35802. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35803. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35804. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35805. }
  35806. }
  35807. // Textures
  35808. if (scene.texturesEnabled) {
  35809. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35810. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35811. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35812. }
  35813. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35814. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35815. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35816. }
  35817. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35818. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35819. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35820. }
  35821. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35822. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35823. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35824. }
  35825. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35826. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35827. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35828. }
  35829. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35830. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35831. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35832. }
  35833. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35834. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35835. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35836. }
  35837. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35838. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35839. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35840. if (scene._mirroredCameraPosition) {
  35841. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35842. }
  35843. else {
  35844. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35845. }
  35846. }
  35847. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35848. var depth = 1.0;
  35849. if (!this._refractionTexture.isCube) {
  35850. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35851. if (this._refractionTexture.depth) {
  35852. depth = this._refractionTexture.depth;
  35853. }
  35854. }
  35855. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35856. }
  35857. }
  35858. // Point size
  35859. if (this.pointsCloud) {
  35860. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35861. }
  35862. if (defines.SPECULARTERM) {
  35863. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35864. }
  35865. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35866. // Diffuse
  35867. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35868. }
  35869. // Textures
  35870. if (scene.texturesEnabled) {
  35871. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35872. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35873. }
  35874. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35875. effect.setTexture("ambientSampler", this._ambientTexture);
  35876. }
  35877. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35878. effect.setTexture("opacitySampler", this._opacityTexture);
  35879. }
  35880. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35881. if (this._reflectionTexture.isCube) {
  35882. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35883. }
  35884. else {
  35885. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35886. }
  35887. }
  35888. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35889. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35890. }
  35891. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35892. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35893. }
  35894. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35895. effect.setTexture("specularSampler", this._specularTexture);
  35896. }
  35897. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35898. effect.setTexture("bumpSampler", this._bumpTexture);
  35899. }
  35900. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35901. var depth = 1.0;
  35902. if (this._refractionTexture.isCube) {
  35903. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35904. }
  35905. else {
  35906. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35907. }
  35908. }
  35909. }
  35910. // Clip plane
  35911. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35912. // Colors
  35913. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35914. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35915. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35916. }
  35917. if (mustRebind || !this.isFrozen) {
  35918. // Lights
  35919. if (scene.lightsEnabled && !this._disableLighting) {
  35920. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35921. }
  35922. // View
  35923. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35924. this.bindView(effect);
  35925. }
  35926. // Fog
  35927. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35928. // Morph targets
  35929. if (defines.NUM_MORPH_INFLUENCERS) {
  35930. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35931. }
  35932. // Log. depth
  35933. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35934. // image processing
  35935. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35936. this._imageProcessingConfiguration.bind(this._activeEffect);
  35937. }
  35938. }
  35939. this._uniformBuffer.update();
  35940. this._afterBind(mesh, this._activeEffect);
  35941. };
  35942. StandardMaterial.prototype.getAnimatables = function () {
  35943. var results = [];
  35944. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35945. results.push(this._diffuseTexture);
  35946. }
  35947. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35948. results.push(this._ambientTexture);
  35949. }
  35950. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35951. results.push(this._opacityTexture);
  35952. }
  35953. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35954. results.push(this._reflectionTexture);
  35955. }
  35956. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35957. results.push(this._emissiveTexture);
  35958. }
  35959. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35960. results.push(this._specularTexture);
  35961. }
  35962. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35963. results.push(this._bumpTexture);
  35964. }
  35965. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35966. results.push(this._lightmapTexture);
  35967. }
  35968. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35969. results.push(this._refractionTexture);
  35970. }
  35971. return results;
  35972. };
  35973. StandardMaterial.prototype.getActiveTextures = function () {
  35974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35975. if (this._diffuseTexture) {
  35976. activeTextures.push(this._diffuseTexture);
  35977. }
  35978. if (this._ambientTexture) {
  35979. activeTextures.push(this._ambientTexture);
  35980. }
  35981. if (this._opacityTexture) {
  35982. activeTextures.push(this._opacityTexture);
  35983. }
  35984. if (this._reflectionTexture) {
  35985. activeTextures.push(this._reflectionTexture);
  35986. }
  35987. if (this._emissiveTexture) {
  35988. activeTextures.push(this._emissiveTexture);
  35989. }
  35990. if (this._specularTexture) {
  35991. activeTextures.push(this._specularTexture);
  35992. }
  35993. if (this._bumpTexture) {
  35994. activeTextures.push(this._bumpTexture);
  35995. }
  35996. if (this._lightmapTexture) {
  35997. activeTextures.push(this._lightmapTexture);
  35998. }
  35999. if (this._refractionTexture) {
  36000. activeTextures.push(this._refractionTexture);
  36001. }
  36002. return activeTextures;
  36003. };
  36004. StandardMaterial.prototype.hasTexture = function (texture) {
  36005. if (_super.prototype.hasTexture.call(this, texture)) {
  36006. return true;
  36007. }
  36008. if (this._diffuseTexture === texture) {
  36009. return true;
  36010. }
  36011. if (this._ambientTexture === texture) {
  36012. return true;
  36013. }
  36014. if (this._opacityTexture === texture) {
  36015. return true;
  36016. }
  36017. if (this._reflectionTexture === texture) {
  36018. return true;
  36019. }
  36020. if (this._emissiveTexture === texture) {
  36021. return true;
  36022. }
  36023. if (this._specularTexture === texture) {
  36024. return true;
  36025. }
  36026. if (this._bumpTexture === texture) {
  36027. return true;
  36028. }
  36029. if (this._lightmapTexture === texture) {
  36030. return true;
  36031. }
  36032. if (this._refractionTexture === texture) {
  36033. return true;
  36034. }
  36035. return false;
  36036. };
  36037. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36038. if (forceDisposeTextures) {
  36039. if (this._diffuseTexture) {
  36040. this._diffuseTexture.dispose();
  36041. }
  36042. if (this._ambientTexture) {
  36043. this._ambientTexture.dispose();
  36044. }
  36045. if (this._opacityTexture) {
  36046. this._opacityTexture.dispose();
  36047. }
  36048. if (this._reflectionTexture) {
  36049. this._reflectionTexture.dispose();
  36050. }
  36051. if (this._emissiveTexture) {
  36052. this._emissiveTexture.dispose();
  36053. }
  36054. if (this._specularTexture) {
  36055. this._specularTexture.dispose();
  36056. }
  36057. if (this._bumpTexture) {
  36058. this._bumpTexture.dispose();
  36059. }
  36060. if (this._lightmapTexture) {
  36061. this._lightmapTexture.dispose();
  36062. }
  36063. if (this._refractionTexture) {
  36064. this._refractionTexture.dispose();
  36065. }
  36066. }
  36067. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36068. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36069. }
  36070. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36071. };
  36072. StandardMaterial.prototype.clone = function (name) {
  36073. var _this = this;
  36074. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36075. result.name = name;
  36076. result.id = name;
  36077. return result;
  36078. };
  36079. StandardMaterial.prototype.serialize = function () {
  36080. return BABYLON.SerializationHelper.Serialize(this);
  36081. };
  36082. // Statics
  36083. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36084. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36085. };
  36086. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36087. get: function () {
  36088. return StandardMaterial._DiffuseTextureEnabled;
  36089. },
  36090. set: function (value) {
  36091. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36092. return;
  36093. }
  36094. StandardMaterial._DiffuseTextureEnabled = value;
  36095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36101. get: function () {
  36102. return StandardMaterial._AmbientTextureEnabled;
  36103. },
  36104. set: function (value) {
  36105. if (StandardMaterial._AmbientTextureEnabled === value) {
  36106. return;
  36107. }
  36108. StandardMaterial._AmbientTextureEnabled = value;
  36109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36110. },
  36111. enumerable: true,
  36112. configurable: true
  36113. });
  36114. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36115. get: function () {
  36116. return StandardMaterial._OpacityTextureEnabled;
  36117. },
  36118. set: function (value) {
  36119. if (StandardMaterial._OpacityTextureEnabled === value) {
  36120. return;
  36121. }
  36122. StandardMaterial._OpacityTextureEnabled = value;
  36123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36129. get: function () {
  36130. return StandardMaterial._ReflectionTextureEnabled;
  36131. },
  36132. set: function (value) {
  36133. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36134. return;
  36135. }
  36136. StandardMaterial._ReflectionTextureEnabled = value;
  36137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36143. get: function () {
  36144. return StandardMaterial._EmissiveTextureEnabled;
  36145. },
  36146. set: function (value) {
  36147. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36148. return;
  36149. }
  36150. StandardMaterial._EmissiveTextureEnabled = value;
  36151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36152. },
  36153. enumerable: true,
  36154. configurable: true
  36155. });
  36156. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36157. get: function () {
  36158. return StandardMaterial._SpecularTextureEnabled;
  36159. },
  36160. set: function (value) {
  36161. if (StandardMaterial._SpecularTextureEnabled === value) {
  36162. return;
  36163. }
  36164. StandardMaterial._SpecularTextureEnabled = value;
  36165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36171. get: function () {
  36172. return StandardMaterial._BumpTextureEnabled;
  36173. },
  36174. set: function (value) {
  36175. if (StandardMaterial._BumpTextureEnabled === value) {
  36176. return;
  36177. }
  36178. StandardMaterial._BumpTextureEnabled = value;
  36179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36180. },
  36181. enumerable: true,
  36182. configurable: true
  36183. });
  36184. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36185. get: function () {
  36186. return StandardMaterial._LightmapTextureEnabled;
  36187. },
  36188. set: function (value) {
  36189. if (StandardMaterial._LightmapTextureEnabled === value) {
  36190. return;
  36191. }
  36192. StandardMaterial._LightmapTextureEnabled = value;
  36193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36199. get: function () {
  36200. return StandardMaterial._RefractionTextureEnabled;
  36201. },
  36202. set: function (value) {
  36203. if (StandardMaterial._RefractionTextureEnabled === value) {
  36204. return;
  36205. }
  36206. StandardMaterial._RefractionTextureEnabled = value;
  36207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36213. get: function () {
  36214. return StandardMaterial._ColorGradingTextureEnabled;
  36215. },
  36216. set: function (value) {
  36217. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36218. return;
  36219. }
  36220. StandardMaterial._ColorGradingTextureEnabled = value;
  36221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36222. },
  36223. enumerable: true,
  36224. configurable: true
  36225. });
  36226. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36227. get: function () {
  36228. return StandardMaterial._FresnelEnabled;
  36229. },
  36230. set: function (value) {
  36231. if (StandardMaterial._FresnelEnabled === value) {
  36232. return;
  36233. }
  36234. StandardMaterial._FresnelEnabled = value;
  36235. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36236. },
  36237. enumerable: true,
  36238. configurable: true
  36239. });
  36240. // Flags used to enable or disable a type of texture for all Standard Materials
  36241. StandardMaterial._DiffuseTextureEnabled = true;
  36242. StandardMaterial._AmbientTextureEnabled = true;
  36243. StandardMaterial._OpacityTextureEnabled = true;
  36244. StandardMaterial._ReflectionTextureEnabled = true;
  36245. StandardMaterial._EmissiveTextureEnabled = true;
  36246. StandardMaterial._SpecularTextureEnabled = true;
  36247. StandardMaterial._BumpTextureEnabled = true;
  36248. StandardMaterial._LightmapTextureEnabled = true;
  36249. StandardMaterial._RefractionTextureEnabled = true;
  36250. StandardMaterial._ColorGradingTextureEnabled = true;
  36251. StandardMaterial._FresnelEnabled = true;
  36252. __decorate([
  36253. BABYLON.serializeAsTexture("diffuseTexture")
  36254. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36255. __decorate([
  36256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36257. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36258. __decorate([
  36259. BABYLON.serializeAsTexture("ambientTexture")
  36260. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36261. __decorate([
  36262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36263. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36264. __decorate([
  36265. BABYLON.serializeAsTexture("opacityTexture")
  36266. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36267. __decorate([
  36268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36269. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36270. __decorate([
  36271. BABYLON.serializeAsTexture("reflectionTexture")
  36272. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36273. __decorate([
  36274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36275. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36276. __decorate([
  36277. BABYLON.serializeAsTexture("emissiveTexture")
  36278. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36279. __decorate([
  36280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36281. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36282. __decorate([
  36283. BABYLON.serializeAsTexture("specularTexture")
  36284. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36285. __decorate([
  36286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36287. ], StandardMaterial.prototype, "specularTexture", void 0);
  36288. __decorate([
  36289. BABYLON.serializeAsTexture("bumpTexture")
  36290. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36291. __decorate([
  36292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36293. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36294. __decorate([
  36295. BABYLON.serializeAsTexture("lightmapTexture")
  36296. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36297. __decorate([
  36298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36299. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36300. __decorate([
  36301. BABYLON.serializeAsTexture("refractionTexture")
  36302. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36303. __decorate([
  36304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36305. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36306. __decorate([
  36307. BABYLON.serializeAsColor3("ambient")
  36308. ], StandardMaterial.prototype, "ambientColor", void 0);
  36309. __decorate([
  36310. BABYLON.serializeAsColor3("diffuse")
  36311. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36312. __decorate([
  36313. BABYLON.serializeAsColor3("specular")
  36314. ], StandardMaterial.prototype, "specularColor", void 0);
  36315. __decorate([
  36316. BABYLON.serializeAsColor3("emissive")
  36317. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36318. __decorate([
  36319. BABYLON.serialize()
  36320. ], StandardMaterial.prototype, "specularPower", void 0);
  36321. __decorate([
  36322. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36323. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36324. __decorate([
  36325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36326. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36327. __decorate([
  36328. BABYLON.serialize("useEmissiveAsIllumination")
  36329. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36330. __decorate([
  36331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36332. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36333. __decorate([
  36334. BABYLON.serialize("linkEmissiveWithDiffuse")
  36335. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36336. __decorate([
  36337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36338. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36339. __decorate([
  36340. BABYLON.serialize("useSpecularOverAlpha")
  36341. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36342. __decorate([
  36343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36344. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36345. __decorate([
  36346. BABYLON.serialize("useReflectionOverAlpha")
  36347. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36348. __decorate([
  36349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36350. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36351. __decorate([
  36352. BABYLON.serialize("disableLighting")
  36353. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36354. __decorate([
  36355. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36356. ], StandardMaterial.prototype, "disableLighting", void 0);
  36357. __decorate([
  36358. BABYLON.serialize("useParallax")
  36359. ], StandardMaterial.prototype, "_useParallax", void 0);
  36360. __decorate([
  36361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36362. ], StandardMaterial.prototype, "useParallax", void 0);
  36363. __decorate([
  36364. BABYLON.serialize("useParallaxOcclusion")
  36365. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36366. __decorate([
  36367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36368. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36369. __decorate([
  36370. BABYLON.serialize()
  36371. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36372. __decorate([
  36373. BABYLON.serialize("roughness")
  36374. ], StandardMaterial.prototype, "_roughness", void 0);
  36375. __decorate([
  36376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36377. ], StandardMaterial.prototype, "roughness", void 0);
  36378. __decorate([
  36379. BABYLON.serialize()
  36380. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36381. __decorate([
  36382. BABYLON.serialize()
  36383. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36384. __decorate([
  36385. BABYLON.serialize("useLightmapAsShadowmap")
  36386. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36387. __decorate([
  36388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36389. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36390. __decorate([
  36391. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36392. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36393. __decorate([
  36394. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36395. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36396. __decorate([
  36397. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36398. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36399. __decorate([
  36400. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36401. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36402. __decorate([
  36403. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36404. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36405. __decorate([
  36406. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36407. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36408. __decorate([
  36409. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36410. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36411. __decorate([
  36412. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36413. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36414. __decorate([
  36415. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36416. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36417. __decorate([
  36418. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36419. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36420. __decorate([
  36421. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36422. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36423. __decorate([
  36424. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36425. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36426. __decorate([
  36427. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36428. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36429. __decorate([
  36430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36431. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36432. __decorate([
  36433. BABYLON.serialize("maxSimultaneousLights")
  36434. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36435. __decorate([
  36436. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36437. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36438. __decorate([
  36439. BABYLON.serialize("invertNormalMapX")
  36440. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36441. __decorate([
  36442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36443. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36444. __decorate([
  36445. BABYLON.serialize("invertNormalMapY")
  36446. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36447. __decorate([
  36448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36449. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36450. __decorate([
  36451. BABYLON.serialize("twoSidedLighting")
  36452. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36453. __decorate([
  36454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36455. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36456. __decorate([
  36457. BABYLON.serialize()
  36458. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36459. return StandardMaterial;
  36460. }(BABYLON.PushMaterial));
  36461. BABYLON.StandardMaterial = StandardMaterial;
  36462. })(BABYLON || (BABYLON = {}));
  36463. //# sourceMappingURL=babylon.standardMaterial.js.map
  36464. var BABYLON;
  36465. (function (BABYLON) {
  36466. var PBRMaterialDefines = /** @class */ (function (_super) {
  36467. __extends(PBRMaterialDefines, _super);
  36468. function PBRMaterialDefines() {
  36469. var _this = _super.call(this) || this;
  36470. _this.PBR = true;
  36471. _this.MAINUV1 = false;
  36472. _this.MAINUV2 = false;
  36473. _this.UV1 = false;
  36474. _this.UV2 = false;
  36475. _this.ALBEDO = false;
  36476. _this.ALBEDODIRECTUV = 0;
  36477. _this.VERTEXCOLOR = false;
  36478. _this.AMBIENT = false;
  36479. _this.AMBIENTDIRECTUV = 0;
  36480. _this.AMBIENTINGRAYSCALE = false;
  36481. _this.OPACITY = false;
  36482. _this.VERTEXALPHA = false;
  36483. _this.OPACITYDIRECTUV = 0;
  36484. _this.OPACITYRGB = false;
  36485. _this.ALPHATEST = false;
  36486. _this.DEPTHPREPASS = false;
  36487. _this.ALPHABLEND = false;
  36488. _this.ALPHAFROMALBEDO = false;
  36489. _this.ALPHATESTVALUE = 0.5;
  36490. _this.SPECULAROVERALPHA = false;
  36491. _this.RADIANCEOVERALPHA = false;
  36492. _this.ALPHAFRESNEL = false;
  36493. _this.LINEARALPHAFRESNEL = false;
  36494. _this.PREMULTIPLYALPHA = false;
  36495. _this.EMISSIVE = false;
  36496. _this.EMISSIVEDIRECTUV = 0;
  36497. _this.REFLECTIVITY = false;
  36498. _this.REFLECTIVITYDIRECTUV = 0;
  36499. _this.SPECULARTERM = false;
  36500. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36501. _this.MICROSURFACEAUTOMATIC = false;
  36502. _this.LODBASEDMICROSFURACE = false;
  36503. _this.MICROSURFACEMAP = false;
  36504. _this.MICROSURFACEMAPDIRECTUV = 0;
  36505. _this.METALLICWORKFLOW = false;
  36506. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36507. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36508. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36509. _this.AOSTOREINMETALMAPRED = false;
  36510. _this.ENVIRONMENTBRDF = false;
  36511. _this.NORMAL = false;
  36512. _this.TANGENT = false;
  36513. _this.BUMP = false;
  36514. _this.BUMPDIRECTUV = 0;
  36515. _this.PARALLAX = false;
  36516. _this.PARALLAXOCCLUSION = false;
  36517. _this.NORMALXYSCALE = true;
  36518. _this.LIGHTMAP = false;
  36519. _this.LIGHTMAPDIRECTUV = 0;
  36520. _this.USELIGHTMAPASSHADOWMAP = false;
  36521. _this.REFLECTION = false;
  36522. _this.REFLECTIONMAP_3D = false;
  36523. _this.REFLECTIONMAP_SPHERICAL = false;
  36524. _this.REFLECTIONMAP_PLANAR = false;
  36525. _this.REFLECTIONMAP_CUBIC = false;
  36526. _this.REFLECTIONMAP_PROJECTION = false;
  36527. _this.REFLECTIONMAP_SKYBOX = false;
  36528. _this.REFLECTIONMAP_EXPLICIT = false;
  36529. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36530. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36531. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36532. _this.INVERTCUBICMAP = false;
  36533. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36534. _this.USESPHERICALINVERTEX = false;
  36535. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36536. _this.LODINREFLECTIONALPHA = false;
  36537. _this.GAMMAREFLECTION = false;
  36538. _this.RADIANCEOCCLUSION = false;
  36539. _this.HORIZONOCCLUSION = false;
  36540. _this.REFRACTION = false;
  36541. _this.REFRACTIONMAP_3D = false;
  36542. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36543. _this.LODINREFRACTIONALPHA = false;
  36544. _this.GAMMAREFRACTION = false;
  36545. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36546. _this.INSTANCES = false;
  36547. _this.NUM_BONE_INFLUENCERS = 0;
  36548. _this.BonesPerMesh = 0;
  36549. _this.NONUNIFORMSCALING = false;
  36550. _this.MORPHTARGETS = false;
  36551. _this.MORPHTARGETS_NORMAL = false;
  36552. _this.MORPHTARGETS_TANGENT = false;
  36553. _this.NUM_MORPH_INFLUENCERS = 0;
  36554. _this.IMAGEPROCESSING = false;
  36555. _this.VIGNETTE = false;
  36556. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36557. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36558. _this.TONEMAPPING = false;
  36559. _this.CONTRAST = false;
  36560. _this.COLORCURVES = false;
  36561. _this.COLORGRADING = false;
  36562. _this.COLORGRADING3D = false;
  36563. _this.SAMPLER3DGREENDEPTH = false;
  36564. _this.SAMPLER3DBGRMAP = false;
  36565. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36566. _this.EXPOSURE = false;
  36567. _this.USEPHYSICALLIGHTFALLOFF = false;
  36568. _this.TWOSIDEDLIGHTING = false;
  36569. _this.SHADOWFLOAT = false;
  36570. _this.CLIPPLANE = false;
  36571. _this.POINTSIZE = false;
  36572. _this.FOG = false;
  36573. _this.LOGARITHMICDEPTH = false;
  36574. _this.FORCENORMALFORWARD = false;
  36575. _this.rebuild();
  36576. return _this;
  36577. }
  36578. PBRMaterialDefines.prototype.reset = function () {
  36579. _super.prototype.reset.call(this);
  36580. this.ALPHATESTVALUE = 0.5;
  36581. this.PBR = true;
  36582. };
  36583. return PBRMaterialDefines;
  36584. }(BABYLON.MaterialDefines));
  36585. /**
  36586. * The Physically based material base class of BJS.
  36587. *
  36588. * This offers the main features of a standard PBR material.
  36589. * For more information, please refer to the documentation :
  36590. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36591. */
  36592. var PBRBaseMaterial = /** @class */ (function (_super) {
  36593. __extends(PBRBaseMaterial, _super);
  36594. /**
  36595. * Instantiates a new PBRMaterial instance.
  36596. *
  36597. * @param name The material name
  36598. * @param scene The scene the material will be use in.
  36599. */
  36600. function PBRBaseMaterial(name, scene) {
  36601. var _this = _super.call(this, name, scene) || this;
  36602. /**
  36603. * Intensity of the direct lights e.g. the four lights available in your scene.
  36604. * This impacts both the direct diffuse and specular highlights.
  36605. */
  36606. _this._directIntensity = 1.0;
  36607. /**
  36608. * Intensity of the emissive part of the material.
  36609. * This helps controlling the emissive effect without modifying the emissive color.
  36610. */
  36611. _this._emissiveIntensity = 1.0;
  36612. /**
  36613. * Intensity of the environment e.g. how much the environment will light the object
  36614. * either through harmonics for rough material or through the refelction for shiny ones.
  36615. */
  36616. _this._environmentIntensity = 1.0;
  36617. /**
  36618. * This is a special control allowing the reduction of the specular highlights coming from the
  36619. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36620. */
  36621. _this._specularIntensity = 1.0;
  36622. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36623. /**
  36624. * Debug Control allowing disabling the bump map on this material.
  36625. */
  36626. _this._disableBumpMap = false;
  36627. /**
  36628. * AKA Occlusion Texture Intensity in other nomenclature.
  36629. */
  36630. _this._ambientTextureStrength = 1.0;
  36631. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36632. /**
  36633. * AKA Diffuse Color in other nomenclature.
  36634. */
  36635. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36636. /**
  36637. * AKA Specular Color in other nomenclature.
  36638. */
  36639. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36640. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36641. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36642. /**
  36643. * AKA Glossiness in other nomenclature.
  36644. */
  36645. _this._microSurface = 0.9;
  36646. /**
  36647. * source material index of refraction (IOR)' / 'destination material IOR.
  36648. */
  36649. _this._indexOfRefraction = 0.66;
  36650. /**
  36651. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36652. */
  36653. _this._invertRefractionY = false;
  36654. /**
  36655. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36656. * Materials half opaque for instance using refraction could benefit from this control.
  36657. */
  36658. _this._linkRefractionWithTransparency = false;
  36659. _this._useLightmapAsShadowmap = false;
  36660. /**
  36661. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36662. * makes the reflect vector face the model (under horizon).
  36663. */
  36664. _this._useHorizonOcclusion = true;
  36665. /**
  36666. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36667. * too much the area relying on ambient texture to define their ambient occlusion.
  36668. */
  36669. _this._useRadianceOcclusion = true;
  36670. /**
  36671. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36672. */
  36673. _this._useAlphaFromAlbedoTexture = false;
  36674. /**
  36675. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36676. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36677. */
  36678. _this._useSpecularOverAlpha = true;
  36679. /**
  36680. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36681. */
  36682. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36683. /**
  36684. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36685. */
  36686. _this._useRoughnessFromMetallicTextureAlpha = true;
  36687. /**
  36688. * Specifies if the metallic texture contains the roughness information in its green channel.
  36689. */
  36690. _this._useRoughnessFromMetallicTextureGreen = false;
  36691. /**
  36692. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36693. */
  36694. _this._useMetallnessFromMetallicTextureBlue = false;
  36695. /**
  36696. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36697. */
  36698. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36699. /**
  36700. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36701. */
  36702. _this._useAmbientInGrayScale = false;
  36703. /**
  36704. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36705. * The material will try to infer what glossiness each pixel should be.
  36706. */
  36707. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36708. /**
  36709. * BJS is using an harcoded light falloff based on a manually sets up range.
  36710. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36711. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36712. */
  36713. _this._usePhysicalLightFalloff = true;
  36714. /**
  36715. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36716. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36717. */
  36718. _this._useRadianceOverAlpha = true;
  36719. /**
  36720. * Allows using the bump map in parallax mode.
  36721. */
  36722. _this._useParallax = false;
  36723. /**
  36724. * Allows using the bump map in parallax occlusion mode.
  36725. */
  36726. _this._useParallaxOcclusion = false;
  36727. /**
  36728. * Controls the scale bias of the parallax mode.
  36729. */
  36730. _this._parallaxScaleBias = 0.05;
  36731. /**
  36732. * If sets to true, disables all the lights affecting the material.
  36733. */
  36734. _this._disableLighting = false;
  36735. /**
  36736. * Number of Simultaneous lights allowed on the material.
  36737. */
  36738. _this._maxSimultaneousLights = 4;
  36739. /**
  36740. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36741. */
  36742. _this._invertNormalMapX = false;
  36743. /**
  36744. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36745. */
  36746. _this._invertNormalMapY = false;
  36747. /**
  36748. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36749. */
  36750. _this._twoSidedLighting = false;
  36751. /**
  36752. * Defines the alpha limits in alpha test mode.
  36753. */
  36754. _this._alphaCutOff = 0.4;
  36755. /**
  36756. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36757. */
  36758. _this._forceAlphaTest = false;
  36759. /**
  36760. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36761. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36762. */
  36763. _this._useAlphaFresnel = false;
  36764. /**
  36765. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36766. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36767. */
  36768. _this._useLinearAlphaFresnel = false;
  36769. /**
  36770. * The transparency mode of the material.
  36771. */
  36772. _this._transparencyMode = null;
  36773. /**
  36774. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36775. * from cos thetav and roughness:
  36776. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36777. */
  36778. _this._environmentBRDFTexture = null;
  36779. /**
  36780. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36781. */
  36782. _this._forceIrradianceInFragment = false;
  36783. /**
  36784. * Force normal to face away from face.
  36785. */
  36786. _this._forceNormalForward = false;
  36787. /**
  36788. * Force metallic workflow.
  36789. */
  36790. _this._forceMetallicWorkflow = false;
  36791. _this._renderTargets = new BABYLON.SmartArray(16);
  36792. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36793. // Setup the default processing configuration to the scene.
  36794. _this._attachImageProcessingConfiguration(null);
  36795. _this.getRenderTargetTextures = function () {
  36796. _this._renderTargets.reset();
  36797. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36798. _this._renderTargets.push(_this._reflectionTexture);
  36799. }
  36800. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36801. _this._renderTargets.push(_this._refractionTexture);
  36802. }
  36803. return _this._renderTargets;
  36804. };
  36805. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36806. return _this;
  36807. }
  36808. /**
  36809. * Attaches a new image processing configuration to the PBR Material.
  36810. * @param configuration
  36811. */
  36812. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36813. var _this = this;
  36814. if (configuration === this._imageProcessingConfiguration) {
  36815. return;
  36816. }
  36817. // Detaches observer.
  36818. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36819. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36820. }
  36821. // Pick the scene configuration if needed.
  36822. if (!configuration) {
  36823. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36824. }
  36825. else {
  36826. this._imageProcessingConfiguration = configuration;
  36827. }
  36828. // Attaches observer.
  36829. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36830. _this._markAllSubMeshesAsImageProcessingDirty();
  36831. });
  36832. };
  36833. PBRBaseMaterial.prototype.getClassName = function () {
  36834. return "PBRBaseMaterial";
  36835. };
  36836. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36837. get: function () {
  36838. return this._useLogarithmicDepth;
  36839. },
  36840. set: function (value) {
  36841. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36842. },
  36843. enumerable: true,
  36844. configurable: true
  36845. });
  36846. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36847. /**
  36848. * Gets the current transparency mode.
  36849. */
  36850. get: function () {
  36851. return this._transparencyMode;
  36852. },
  36853. /**
  36854. * Sets the transparency mode of the material.
  36855. */
  36856. set: function (value) {
  36857. if (this._transparencyMode === value) {
  36858. return;
  36859. }
  36860. this._transparencyMode = value;
  36861. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36862. this._markAllSubMeshesAsTexturesDirty();
  36863. },
  36864. enumerable: true,
  36865. configurable: true
  36866. });
  36867. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36868. /**
  36869. * Returns true if alpha blending should be disabled.
  36870. */
  36871. get: function () {
  36872. return (this._linkRefractionWithTransparency ||
  36873. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36874. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36875. },
  36876. enumerable: true,
  36877. configurable: true
  36878. });
  36879. /**
  36880. * Specifies whether or not this material should be rendered in alpha blend mode.
  36881. */
  36882. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36883. if (this._disableAlphaBlending) {
  36884. return false;
  36885. }
  36886. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36887. };
  36888. /**
  36889. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36890. */
  36891. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36892. if (this._disableAlphaBlending) {
  36893. return false;
  36894. }
  36895. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36896. };
  36897. /**
  36898. * Specifies whether or not this material should be rendered in alpha test mode.
  36899. */
  36900. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36901. if (this._forceAlphaTest) {
  36902. return true;
  36903. }
  36904. if (this._linkRefractionWithTransparency) {
  36905. return false;
  36906. }
  36907. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36908. };
  36909. /**
  36910. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36911. */
  36912. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36913. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36914. };
  36915. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36916. return this._albedoTexture;
  36917. };
  36918. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36919. var _this = this;
  36920. if (subMesh.effect && this.isFrozen) {
  36921. if (this._wasPreviouslyReady) {
  36922. return true;
  36923. }
  36924. }
  36925. if (!subMesh._materialDefines) {
  36926. subMesh._materialDefines = new PBRMaterialDefines();
  36927. }
  36928. var scene = this.getScene();
  36929. var defines = subMesh._materialDefines;
  36930. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36931. if (defines._renderId === scene.getRenderId()) {
  36932. return true;
  36933. }
  36934. }
  36935. var engine = scene.getEngine();
  36936. // Lights
  36937. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36938. defines._needNormals = true;
  36939. // Textures
  36940. if (defines._areTexturesDirty) {
  36941. defines._needUVs = false;
  36942. if (scene.texturesEnabled) {
  36943. if (scene.getEngine().getCaps().textureLOD) {
  36944. defines.LODBASEDMICROSFURACE = true;
  36945. }
  36946. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36947. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36948. return false;
  36949. }
  36950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36951. }
  36952. else {
  36953. defines.ALBEDO = false;
  36954. }
  36955. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36956. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36957. return false;
  36958. }
  36959. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36960. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36961. }
  36962. else {
  36963. defines.AMBIENT = false;
  36964. }
  36965. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36966. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36967. return false;
  36968. }
  36969. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36970. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36971. }
  36972. else {
  36973. defines.OPACITY = false;
  36974. }
  36975. var reflectionTexture = this._getReflectionTexture();
  36976. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36977. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36978. return false;
  36979. }
  36980. defines.REFLECTION = true;
  36981. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36982. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36983. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36984. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36985. defines.INVERTCUBICMAP = true;
  36986. }
  36987. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36988. switch (reflectionTexture.coordinatesMode) {
  36989. case BABYLON.Texture.CUBIC_MODE:
  36990. case BABYLON.Texture.INVCUBIC_MODE:
  36991. defines.REFLECTIONMAP_CUBIC = true;
  36992. break;
  36993. case BABYLON.Texture.EXPLICIT_MODE:
  36994. defines.REFLECTIONMAP_EXPLICIT = true;
  36995. break;
  36996. case BABYLON.Texture.PLANAR_MODE:
  36997. defines.REFLECTIONMAP_PLANAR = true;
  36998. break;
  36999. case BABYLON.Texture.PROJECTION_MODE:
  37000. defines.REFLECTIONMAP_PROJECTION = true;
  37001. break;
  37002. case BABYLON.Texture.SKYBOX_MODE:
  37003. defines.REFLECTIONMAP_SKYBOX = true;
  37004. break;
  37005. case BABYLON.Texture.SPHERICAL_MODE:
  37006. defines.REFLECTIONMAP_SPHERICAL = true;
  37007. break;
  37008. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37009. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37010. break;
  37011. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37012. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37013. break;
  37014. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37015. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37016. break;
  37017. }
  37018. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37019. if (reflectionTexture.sphericalPolynomial) {
  37020. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37021. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37022. defines.USESPHERICALINVERTEX = false;
  37023. }
  37024. else {
  37025. defines.USESPHERICALINVERTEX = true;
  37026. }
  37027. }
  37028. }
  37029. }
  37030. else {
  37031. defines.REFLECTION = false;
  37032. defines.REFLECTIONMAP_3D = false;
  37033. defines.REFLECTIONMAP_SPHERICAL = false;
  37034. defines.REFLECTIONMAP_PLANAR = false;
  37035. defines.REFLECTIONMAP_CUBIC = false;
  37036. defines.REFLECTIONMAP_PROJECTION = false;
  37037. defines.REFLECTIONMAP_SKYBOX = false;
  37038. defines.REFLECTIONMAP_EXPLICIT = false;
  37039. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37040. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37041. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37042. defines.INVERTCUBICMAP = false;
  37043. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37044. defines.USESPHERICALINVERTEX = false;
  37045. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37046. defines.LODINREFLECTIONALPHA = false;
  37047. defines.GAMMAREFLECTION = false;
  37048. }
  37049. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37050. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37051. return false;
  37052. }
  37053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37054. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37055. }
  37056. else {
  37057. defines.LIGHTMAP = false;
  37058. }
  37059. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37060. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37061. return false;
  37062. }
  37063. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37064. }
  37065. else {
  37066. defines.EMISSIVE = false;
  37067. }
  37068. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37069. if (this._metallicTexture) {
  37070. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37071. return false;
  37072. }
  37073. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37074. defines.METALLICWORKFLOW = true;
  37075. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37076. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37077. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37078. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37079. }
  37080. else if (this._reflectivityTexture) {
  37081. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37082. return false;
  37083. }
  37084. defines.METALLICWORKFLOW = false;
  37085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37086. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37087. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37088. }
  37089. else {
  37090. defines.METALLICWORKFLOW = false;
  37091. defines.REFLECTIVITY = false;
  37092. }
  37093. if (this._microSurfaceTexture) {
  37094. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37095. return false;
  37096. }
  37097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37098. }
  37099. else {
  37100. defines.MICROSURFACEMAP = false;
  37101. }
  37102. }
  37103. else {
  37104. defines.REFLECTIVITY = false;
  37105. defines.MICROSURFACEMAP = false;
  37106. }
  37107. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37108. // Bump texure can not be none blocking.
  37109. if (!this._bumpTexture.isReady()) {
  37110. return false;
  37111. }
  37112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37113. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37114. defines.PARALLAX = true;
  37115. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37116. }
  37117. else {
  37118. defines.PARALLAX = false;
  37119. }
  37120. }
  37121. else {
  37122. defines.BUMP = false;
  37123. }
  37124. var refractionTexture = this._getRefractionTexture();
  37125. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37126. if (!refractionTexture.isReadyOrNotBlocking()) {
  37127. return false;
  37128. }
  37129. defines.REFRACTION = true;
  37130. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37131. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37132. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37133. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37134. if (this._linkRefractionWithTransparency) {
  37135. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37136. }
  37137. }
  37138. else {
  37139. defines.REFRACTION = false;
  37140. }
  37141. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37142. // This is blocking.
  37143. if (!this._environmentBRDFTexture.isReady()) {
  37144. return false;
  37145. }
  37146. defines.ENVIRONMENTBRDF = true;
  37147. }
  37148. else {
  37149. defines.ENVIRONMENTBRDF = false;
  37150. }
  37151. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37152. defines.ALPHAFROMALBEDO = true;
  37153. }
  37154. else {
  37155. defines.ALPHAFROMALBEDO = false;
  37156. }
  37157. }
  37158. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37159. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37160. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37161. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37162. defines.METALLICWORKFLOW = true;
  37163. }
  37164. else {
  37165. defines.METALLICWORKFLOW = false;
  37166. }
  37167. if (!this.backFaceCulling && this._twoSidedLighting) {
  37168. defines.TWOSIDEDLIGHTING = true;
  37169. }
  37170. else {
  37171. defines.TWOSIDEDLIGHTING = false;
  37172. }
  37173. defines.ALPHATESTVALUE = this._alphaCutOff;
  37174. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37175. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37176. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37177. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37178. }
  37179. if (defines._areImageProcessingDirty) {
  37180. if (!this._imageProcessingConfiguration.isReady()) {
  37181. return false;
  37182. }
  37183. this._imageProcessingConfiguration.prepareDefines(defines);
  37184. }
  37185. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37186. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37187. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37188. // Misc.
  37189. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37190. // Values that need to be evaluated on every frame
  37191. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  37192. // Attribs
  37193. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37194. var bufferMesh = null;
  37195. if (mesh instanceof BABYLON.InstancedMesh) {
  37196. bufferMesh = mesh.sourceMesh;
  37197. }
  37198. else if (mesh instanceof BABYLON.Mesh) {
  37199. bufferMesh = mesh;
  37200. }
  37201. if (bufferMesh) {
  37202. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37203. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37204. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37205. var normals = normalVertexBuffer.getData();
  37206. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37207. var strideSize = normalVertexBuffer.getStrideSize();
  37208. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37209. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37210. defines.NORMAL = false;
  37211. }
  37212. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37213. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37214. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37215. var tangents = tangentVertexBuffer.getData();
  37216. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37217. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37218. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37219. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37220. defines.TANGENT = false;
  37221. }
  37222. }
  37223. }
  37224. else {
  37225. if (!scene.getEngine().getCaps().standardDerivatives) {
  37226. bufferMesh.createNormals(true);
  37227. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37228. }
  37229. }
  37230. }
  37231. }
  37232. // Get correct effect
  37233. if (defines.isDirty) {
  37234. defines.markAsProcessed();
  37235. scene.resetCachedMaterial();
  37236. // Fallbacks
  37237. var fallbacks = new BABYLON.EffectFallbacks();
  37238. var fallbackRank = 0;
  37239. if (defines.USESPHERICALINVERTEX) {
  37240. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37241. }
  37242. if (defines.FOG) {
  37243. fallbacks.addFallback(fallbackRank, "FOG");
  37244. }
  37245. if (defines.POINTSIZE) {
  37246. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37247. }
  37248. if (defines.LOGARITHMICDEPTH) {
  37249. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37250. }
  37251. if (defines.PARALLAX) {
  37252. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37253. }
  37254. if (defines.PARALLAXOCCLUSION) {
  37255. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37256. }
  37257. if (defines.ENVIRONMENTBRDF) {
  37258. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37259. }
  37260. if (defines.TANGENT) {
  37261. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37262. }
  37263. if (defines.BUMP) {
  37264. fallbacks.addFallback(fallbackRank++, "BUMP");
  37265. }
  37266. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37267. if (defines.SPECULARTERM) {
  37268. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37269. }
  37270. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37271. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37272. }
  37273. if (defines.LIGHTMAP) {
  37274. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37275. }
  37276. if (defines.NORMAL) {
  37277. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37278. }
  37279. if (defines.AMBIENT) {
  37280. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37281. }
  37282. if (defines.EMISSIVE) {
  37283. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37284. }
  37285. if (defines.VERTEXCOLOR) {
  37286. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37287. }
  37288. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37289. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37290. }
  37291. if (defines.MORPHTARGETS) {
  37292. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37293. }
  37294. //Attributes
  37295. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37296. if (defines.NORMAL) {
  37297. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37298. }
  37299. if (defines.TANGENT) {
  37300. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37301. }
  37302. if (defines.UV1) {
  37303. attribs.push(BABYLON.VertexBuffer.UVKind);
  37304. }
  37305. if (defines.UV2) {
  37306. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37307. }
  37308. if (defines.VERTEXCOLOR) {
  37309. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37310. }
  37311. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37312. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37313. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37314. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37315. "vFogInfos", "vFogColor", "pointSize",
  37316. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37317. "mBones",
  37318. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37319. "vLightingIntensity",
  37320. "logarithmicDepthConstant",
  37321. "vSphericalX", "vSphericalY", "vSphericalZ",
  37322. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37323. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37324. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37325. "vTangentSpaceParams"
  37326. ];
  37327. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37328. "bumpSampler", "lightmapSampler", "opacitySampler",
  37329. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37330. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37331. "microSurfaceSampler", "environmentBrdfSampler"];
  37332. var uniformBuffers = ["Material", "Scene"];
  37333. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37334. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37335. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37336. uniformsNames: uniforms,
  37337. uniformBuffersNames: uniformBuffers,
  37338. samplers: samplers,
  37339. defines: defines,
  37340. maxSimultaneousLights: this._maxSimultaneousLights
  37341. });
  37342. var onCompiled = function (effect) {
  37343. if (_this.onCompiled) {
  37344. _this.onCompiled(effect);
  37345. }
  37346. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37347. };
  37348. var join = defines.toString();
  37349. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37350. attributes: attribs,
  37351. uniformsNames: uniforms,
  37352. uniformBuffersNames: uniformBuffers,
  37353. samplers: samplers,
  37354. defines: join,
  37355. fallbacks: fallbacks,
  37356. onCompiled: onCompiled,
  37357. onError: this.onError,
  37358. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37359. }, engine), defines);
  37360. this.buildUniformLayout();
  37361. }
  37362. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37363. return false;
  37364. }
  37365. defines._renderId = scene.getRenderId();
  37366. this._wasPreviouslyReady = true;
  37367. return true;
  37368. };
  37369. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37370. // Order is important !
  37371. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37372. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37373. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37374. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37375. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37376. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37377. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37378. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37379. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37380. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37381. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37382. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37383. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37384. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37385. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37386. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37387. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37388. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37389. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37390. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37391. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37392. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37393. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37394. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37395. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37396. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37397. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37398. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37399. this._uniformBuffer.addUniform("pointSize", 1);
  37400. this._uniformBuffer.create();
  37401. };
  37402. PBRBaseMaterial.prototype.unbind = function () {
  37403. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37404. this._uniformBuffer.setTexture("reflectionSampler", null);
  37405. }
  37406. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37407. this._uniformBuffer.setTexture("refractionSampler", null);
  37408. }
  37409. _super.prototype.unbind.call(this);
  37410. };
  37411. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37412. this._activeEffect.setMatrix("world", world);
  37413. };
  37414. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37415. var scene = this.getScene();
  37416. var defines = subMesh._materialDefines;
  37417. if (!defines) {
  37418. return;
  37419. }
  37420. var effect = subMesh.effect;
  37421. if (!effect) {
  37422. return;
  37423. }
  37424. this._activeEffect = effect;
  37425. // Matrices
  37426. this.bindOnlyWorldMatrix(world);
  37427. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37428. // Bones
  37429. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37430. var reflectionTexture = null;
  37431. if (mustRebind) {
  37432. this._uniformBuffer.bindToEffect(effect, "Material");
  37433. this.bindViewProjection(effect);
  37434. reflectionTexture = this._getReflectionTexture();
  37435. var refractionTexture = this._getRefractionTexture();
  37436. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37437. // Texture uniforms
  37438. if (scene.texturesEnabled) {
  37439. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37440. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37441. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37442. }
  37443. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37444. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37445. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37446. }
  37447. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37448. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37449. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37450. }
  37451. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37452. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37453. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37454. var polynomials = reflectionTexture.sphericalPolynomial;
  37455. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37456. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37457. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37458. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37459. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37460. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37461. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37462. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37463. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37464. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37465. }
  37466. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37467. }
  37468. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37469. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37470. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37471. }
  37472. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37473. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37474. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37475. }
  37476. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37477. if (this._metallicTexture) {
  37478. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37479. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37480. }
  37481. else if (this._reflectivityTexture) {
  37482. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37483. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37484. }
  37485. if (this._microSurfaceTexture) {
  37486. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37487. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37488. }
  37489. }
  37490. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37491. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37492. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37493. if (scene._mirroredCameraPosition) {
  37494. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37495. }
  37496. else {
  37497. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37498. }
  37499. }
  37500. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37501. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37502. var depth = 1.0;
  37503. if (!refractionTexture.isCube) {
  37504. if (refractionTexture.depth) {
  37505. depth = refractionTexture.depth;
  37506. }
  37507. }
  37508. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37509. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37510. }
  37511. }
  37512. // Point size
  37513. if (this.pointsCloud) {
  37514. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37515. }
  37516. // Colors
  37517. if (defines.METALLICWORKFLOW) {
  37518. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37519. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37520. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37521. }
  37522. else {
  37523. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37524. }
  37525. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37526. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37527. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37528. // Misc
  37529. this._lightingInfos.x = this._directIntensity;
  37530. this._lightingInfos.y = this._emissiveIntensity;
  37531. this._lightingInfos.z = this._environmentIntensity;
  37532. this._lightingInfos.w = this._specularIntensity;
  37533. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37534. }
  37535. // Textures
  37536. if (scene.texturesEnabled) {
  37537. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37538. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37539. }
  37540. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37541. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37542. }
  37543. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37544. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37545. }
  37546. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37547. if (defines.LODBASEDMICROSFURACE) {
  37548. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37549. }
  37550. else {
  37551. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37552. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37553. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37554. }
  37555. }
  37556. if (defines.ENVIRONMENTBRDF) {
  37557. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37558. }
  37559. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37560. if (defines.LODBASEDMICROSFURACE) {
  37561. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37562. }
  37563. else {
  37564. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37565. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37566. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37567. }
  37568. }
  37569. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37570. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37571. }
  37572. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37573. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37574. }
  37575. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37576. if (this._metallicTexture) {
  37577. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37578. }
  37579. else if (this._reflectivityTexture) {
  37580. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37581. }
  37582. if (this._microSurfaceTexture) {
  37583. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37584. }
  37585. }
  37586. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37587. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37588. }
  37589. }
  37590. // Clip plane
  37591. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37592. // Colors
  37593. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37594. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37595. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37596. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37597. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37598. }
  37599. if (mustRebind || !this.isFrozen) {
  37600. // Lights
  37601. if (scene.lightsEnabled && !this._disableLighting) {
  37602. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37603. }
  37604. // View
  37605. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37606. this.bindView(effect);
  37607. }
  37608. // Fog
  37609. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37610. // Morph targets
  37611. if (defines.NUM_MORPH_INFLUENCERS) {
  37612. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37613. }
  37614. // image processing
  37615. this._imageProcessingConfiguration.bind(this._activeEffect);
  37616. // Log. depth
  37617. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37618. }
  37619. this._uniformBuffer.update();
  37620. this._afterBind(mesh);
  37621. };
  37622. PBRBaseMaterial.prototype.getAnimatables = function () {
  37623. var results = [];
  37624. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37625. results.push(this._albedoTexture);
  37626. }
  37627. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37628. results.push(this._ambientTexture);
  37629. }
  37630. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37631. results.push(this._opacityTexture);
  37632. }
  37633. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37634. results.push(this._reflectionTexture);
  37635. }
  37636. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37637. results.push(this._emissiveTexture);
  37638. }
  37639. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37640. results.push(this._metallicTexture);
  37641. }
  37642. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37643. results.push(this._reflectivityTexture);
  37644. }
  37645. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37646. results.push(this._bumpTexture);
  37647. }
  37648. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37649. results.push(this._lightmapTexture);
  37650. }
  37651. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37652. results.push(this._refractionTexture);
  37653. }
  37654. return results;
  37655. };
  37656. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37657. if (this._reflectionTexture) {
  37658. return this._reflectionTexture;
  37659. }
  37660. return this.getScene().environmentTexture;
  37661. };
  37662. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37663. if (this._refractionTexture) {
  37664. return this._refractionTexture;
  37665. }
  37666. if (this._linkRefractionWithTransparency) {
  37667. return this.getScene().environmentTexture;
  37668. }
  37669. return null;
  37670. };
  37671. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37672. if (forceDisposeTextures) {
  37673. if (this._albedoTexture) {
  37674. this._albedoTexture.dispose();
  37675. }
  37676. if (this._ambientTexture) {
  37677. this._ambientTexture.dispose();
  37678. }
  37679. if (this._opacityTexture) {
  37680. this._opacityTexture.dispose();
  37681. }
  37682. if (this._reflectionTexture) {
  37683. this._reflectionTexture.dispose();
  37684. }
  37685. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37686. this._environmentBRDFTexture.dispose();
  37687. }
  37688. if (this._emissiveTexture) {
  37689. this._emissiveTexture.dispose();
  37690. }
  37691. if (this._metallicTexture) {
  37692. this._metallicTexture.dispose();
  37693. }
  37694. if (this._reflectivityTexture) {
  37695. this._reflectivityTexture.dispose();
  37696. }
  37697. if (this._bumpTexture) {
  37698. this._bumpTexture.dispose();
  37699. }
  37700. if (this._lightmapTexture) {
  37701. this._lightmapTexture.dispose();
  37702. }
  37703. if (this._refractionTexture) {
  37704. this._refractionTexture.dispose();
  37705. }
  37706. }
  37707. this._renderTargets.dispose();
  37708. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37709. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37710. }
  37711. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37712. };
  37713. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37714. __decorate([
  37715. BABYLON.serializeAsImageProcessingConfiguration()
  37716. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37717. __decorate([
  37718. BABYLON.serialize()
  37719. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37720. __decorate([
  37721. BABYLON.serialize()
  37722. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37723. return PBRBaseMaterial;
  37724. }(BABYLON.PushMaterial));
  37725. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37726. })(BABYLON || (BABYLON = {}));
  37727. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37728. var BABYLON;
  37729. (function (BABYLON) {
  37730. /**
  37731. * The Physically based simple base material of BJS.
  37732. *
  37733. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37734. * It is used as the base class for both the specGloss and metalRough conventions.
  37735. */
  37736. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37737. __extends(PBRBaseSimpleMaterial, _super);
  37738. /**
  37739. * Instantiates a new PBRMaterial instance.
  37740. *
  37741. * @param name The material name
  37742. * @param scene The scene the material will be use in.
  37743. */
  37744. function PBRBaseSimpleMaterial(name, scene) {
  37745. var _this = _super.call(this, name, scene) || this;
  37746. /**
  37747. * Number of Simultaneous lights allowed on the material.
  37748. */
  37749. _this.maxSimultaneousLights = 4;
  37750. /**
  37751. * If sets to true, disables all the lights affecting the material.
  37752. */
  37753. _this.disableLighting = false;
  37754. /**
  37755. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37756. */
  37757. _this.invertNormalMapX = false;
  37758. /**
  37759. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37760. */
  37761. _this.invertNormalMapY = false;
  37762. /**
  37763. * Emissivie color used to self-illuminate the model.
  37764. */
  37765. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37766. /**
  37767. * Occlusion Channel Strenght.
  37768. */
  37769. _this.occlusionStrength = 1.0;
  37770. _this.useLightmapAsShadowmap = false;
  37771. _this._useAlphaFromAlbedoTexture = true;
  37772. _this._useAmbientInGrayScale = true;
  37773. return _this;
  37774. }
  37775. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37776. /**
  37777. * Gets the current double sided mode.
  37778. */
  37779. get: function () {
  37780. return this._twoSidedLighting;
  37781. },
  37782. /**
  37783. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37784. */
  37785. set: function (value) {
  37786. if (this._twoSidedLighting === value) {
  37787. return;
  37788. }
  37789. this._twoSidedLighting = value;
  37790. this.backFaceCulling = !value;
  37791. this._markAllSubMeshesAsTexturesDirty();
  37792. },
  37793. enumerable: true,
  37794. configurable: true
  37795. });
  37796. /**
  37797. * Return the active textures of the material.
  37798. */
  37799. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37800. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37801. if (this.environmentTexture) {
  37802. activeTextures.push(this.environmentTexture);
  37803. }
  37804. if (this.normalTexture) {
  37805. activeTextures.push(this.normalTexture);
  37806. }
  37807. if (this.emissiveTexture) {
  37808. activeTextures.push(this.emissiveTexture);
  37809. }
  37810. if (this.occlusionTexture) {
  37811. activeTextures.push(this.occlusionTexture);
  37812. }
  37813. if (this.lightmapTexture) {
  37814. activeTextures.push(this.lightmapTexture);
  37815. }
  37816. return activeTextures;
  37817. };
  37818. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37819. if (_super.prototype.hasTexture.call(this, texture)) {
  37820. return true;
  37821. }
  37822. if (this.lightmapTexture === texture) {
  37823. return true;
  37824. }
  37825. return false;
  37826. };
  37827. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37828. return "PBRBaseSimpleMaterial";
  37829. };
  37830. __decorate([
  37831. BABYLON.serialize(),
  37832. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37833. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37834. __decorate([
  37835. BABYLON.serialize(),
  37836. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37837. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37838. __decorate([
  37839. BABYLON.serializeAsTexture(),
  37840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37841. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37842. __decorate([
  37843. BABYLON.serialize(),
  37844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37845. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37846. __decorate([
  37847. BABYLON.serialize(),
  37848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37849. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37850. __decorate([
  37851. BABYLON.serializeAsTexture(),
  37852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37853. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37854. __decorate([
  37855. BABYLON.serializeAsColor3("emissive"),
  37856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37857. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37858. __decorate([
  37859. BABYLON.serializeAsTexture(),
  37860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37861. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37862. __decorate([
  37863. BABYLON.serialize(),
  37864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37865. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37866. __decorate([
  37867. BABYLON.serializeAsTexture(),
  37868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37869. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37870. __decorate([
  37871. BABYLON.serialize(),
  37872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37873. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37874. __decorate([
  37875. BABYLON.serialize()
  37876. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37877. __decorate([
  37878. BABYLON.serializeAsTexture(),
  37879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37880. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37881. __decorate([
  37882. BABYLON.serialize(),
  37883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37884. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37885. return PBRBaseSimpleMaterial;
  37886. }(BABYLON.PBRBaseMaterial));
  37887. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37888. })(BABYLON || (BABYLON = {}));
  37889. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37890. var BABYLON;
  37891. (function (BABYLON) {
  37892. /**
  37893. * The Physically based material of BJS.
  37894. *
  37895. * This offers the main features of a standard PBR material.
  37896. * For more information, please refer to the documentation :
  37897. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37898. */
  37899. var PBRMaterial = /** @class */ (function (_super) {
  37900. __extends(PBRMaterial, _super);
  37901. /**
  37902. * Instantiates a new PBRMaterial instance.
  37903. *
  37904. * @param name The material name
  37905. * @param scene The scene the material will be use in.
  37906. */
  37907. function PBRMaterial(name, scene) {
  37908. var _this = _super.call(this, name, scene) || this;
  37909. /**
  37910. * Intensity of the direct lights e.g. the four lights available in your scene.
  37911. * This impacts both the direct diffuse and specular highlights.
  37912. */
  37913. _this.directIntensity = 1.0;
  37914. /**
  37915. * Intensity of the emissive part of the material.
  37916. * This helps controlling the emissive effect without modifying the emissive color.
  37917. */
  37918. _this.emissiveIntensity = 1.0;
  37919. /**
  37920. * Intensity of the environment e.g. how much the environment will light the object
  37921. * either through harmonics for rough material or through the refelction for shiny ones.
  37922. */
  37923. _this.environmentIntensity = 1.0;
  37924. /**
  37925. * This is a special control allowing the reduction of the specular highlights coming from the
  37926. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37927. */
  37928. _this.specularIntensity = 1.0;
  37929. /**
  37930. * Debug Control allowing disabling the bump map on this material.
  37931. */
  37932. _this.disableBumpMap = false;
  37933. /**
  37934. * AKA Occlusion Texture Intensity in other nomenclature.
  37935. */
  37936. _this.ambientTextureStrength = 1.0;
  37937. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37938. /**
  37939. * AKA Diffuse Color in other nomenclature.
  37940. */
  37941. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37942. /**
  37943. * AKA Specular Color in other nomenclature.
  37944. */
  37945. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37946. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37947. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37948. /**
  37949. * AKA Glossiness in other nomenclature.
  37950. */
  37951. _this.microSurface = 1.0;
  37952. /**
  37953. * source material index of refraction (IOR)' / 'destination material IOR.
  37954. */
  37955. _this.indexOfRefraction = 0.66;
  37956. /**
  37957. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37958. */
  37959. _this.invertRefractionY = false;
  37960. /**
  37961. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37962. * Materials half opaque for instance using refraction could benefit from this control.
  37963. */
  37964. _this.linkRefractionWithTransparency = false;
  37965. _this.useLightmapAsShadowmap = false;
  37966. /**
  37967. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37968. */
  37969. _this.useAlphaFromAlbedoTexture = false;
  37970. /**
  37971. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37972. */
  37973. _this.forceAlphaTest = false;
  37974. /**
  37975. * Defines the alpha limits in alpha test mode.
  37976. */
  37977. _this.alphaCutOff = 0.4;
  37978. /**
  37979. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37980. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37981. */
  37982. _this.useSpecularOverAlpha = true;
  37983. /**
  37984. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37985. */
  37986. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37987. /**
  37988. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37989. */
  37990. _this.useRoughnessFromMetallicTextureAlpha = true;
  37991. /**
  37992. * Specifies if the metallic texture contains the roughness information in its green channel.
  37993. */
  37994. _this.useRoughnessFromMetallicTextureGreen = false;
  37995. /**
  37996. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37997. */
  37998. _this.useMetallnessFromMetallicTextureBlue = false;
  37999. /**
  38000. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38001. */
  38002. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38003. /**
  38004. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38005. */
  38006. _this.useAmbientInGrayScale = false;
  38007. /**
  38008. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38009. * The material will try to infer what glossiness each pixel should be.
  38010. */
  38011. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38012. /**
  38013. * BJS is using an harcoded light falloff based on a manually sets up range.
  38014. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38015. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38016. */
  38017. _this.usePhysicalLightFalloff = true;
  38018. /**
  38019. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38020. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38021. */
  38022. _this.useRadianceOverAlpha = true;
  38023. /**
  38024. * Allows using the bump map in parallax mode.
  38025. */
  38026. _this.useParallax = false;
  38027. /**
  38028. * Allows using the bump map in parallax occlusion mode.
  38029. */
  38030. _this.useParallaxOcclusion = false;
  38031. /**
  38032. * Controls the scale bias of the parallax mode.
  38033. */
  38034. _this.parallaxScaleBias = 0.05;
  38035. /**
  38036. * If sets to true, disables all the lights affecting the material.
  38037. */
  38038. _this.disableLighting = false;
  38039. /**
  38040. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38041. */
  38042. _this.forceIrradianceInFragment = false;
  38043. /**
  38044. * Number of Simultaneous lights allowed on the material.
  38045. */
  38046. _this.maxSimultaneousLights = 4;
  38047. /**
  38048. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38049. */
  38050. _this.invertNormalMapX = false;
  38051. /**
  38052. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38053. */
  38054. _this.invertNormalMapY = false;
  38055. /**
  38056. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38057. */
  38058. _this.twoSidedLighting = false;
  38059. /**
  38060. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38061. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38062. */
  38063. _this.useAlphaFresnel = false;
  38064. /**
  38065. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38066. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38067. */
  38068. _this.useLinearAlphaFresnel = false;
  38069. /**
  38070. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38071. * And/Or occlude the blended part.
  38072. */
  38073. _this.environmentBRDFTexture = null;
  38074. /**
  38075. * Force normal to face away from face.
  38076. */
  38077. _this.forceNormalForward = false;
  38078. /**
  38079. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38080. * makes the reflect vector face the model (under horizon).
  38081. */
  38082. _this.useHorizonOcclusion = true;
  38083. /**
  38084. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38085. * too much the area relying on ambient texture to define their ambient occlusion.
  38086. */
  38087. _this.useRadianceOcclusion = true;
  38088. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38089. return _this;
  38090. }
  38091. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38092. /**
  38093. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38094. */
  38095. get: function () {
  38096. return this._PBRMATERIAL_OPAQUE;
  38097. },
  38098. enumerable: true,
  38099. configurable: true
  38100. });
  38101. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38102. /**
  38103. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38104. */
  38105. get: function () {
  38106. return this._PBRMATERIAL_ALPHATEST;
  38107. },
  38108. enumerable: true,
  38109. configurable: true
  38110. });
  38111. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38112. /**
  38113. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38114. */
  38115. get: function () {
  38116. return this._PBRMATERIAL_ALPHABLEND;
  38117. },
  38118. enumerable: true,
  38119. configurable: true
  38120. });
  38121. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38122. /**
  38123. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38124. * They are also discarded below the alpha cutoff threshold to improve performances.
  38125. */
  38126. get: function () {
  38127. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38128. },
  38129. enumerable: true,
  38130. configurable: true
  38131. });
  38132. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38133. /**
  38134. * Gets the image processing configuration used either in this material.
  38135. */
  38136. get: function () {
  38137. return this._imageProcessingConfiguration;
  38138. },
  38139. /**
  38140. * Sets the Default image processing configuration used either in the this material.
  38141. *
  38142. * If sets to null, the scene one is in use.
  38143. */
  38144. set: function (value) {
  38145. this._attachImageProcessingConfiguration(value);
  38146. // Ensure the effect will be rebuilt.
  38147. this._markAllSubMeshesAsTexturesDirty();
  38148. },
  38149. enumerable: true,
  38150. configurable: true
  38151. });
  38152. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38153. /**
  38154. * Gets wether the color curves effect is enabled.
  38155. */
  38156. get: function () {
  38157. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38158. },
  38159. /**
  38160. * Sets wether the color curves effect is enabled.
  38161. */
  38162. set: function (value) {
  38163. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38169. /**
  38170. * Gets wether the color grading effect is enabled.
  38171. */
  38172. get: function () {
  38173. return this.imageProcessingConfiguration.colorGradingEnabled;
  38174. },
  38175. /**
  38176. * Gets wether the color grading effect is enabled.
  38177. */
  38178. set: function (value) {
  38179. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38180. },
  38181. enumerable: true,
  38182. configurable: true
  38183. });
  38184. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38185. /**
  38186. * Gets wether tonemapping is enabled or not.
  38187. */
  38188. get: function () {
  38189. return this._imageProcessingConfiguration.toneMappingEnabled;
  38190. },
  38191. /**
  38192. * Sets wether tonemapping is enabled or not
  38193. */
  38194. set: function (value) {
  38195. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38196. },
  38197. enumerable: true,
  38198. configurable: true
  38199. });
  38200. ;
  38201. ;
  38202. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38203. /**
  38204. * The camera exposure used on this material.
  38205. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38206. * This corresponds to a photographic exposure.
  38207. */
  38208. get: function () {
  38209. return this._imageProcessingConfiguration.exposure;
  38210. },
  38211. /**
  38212. * The camera exposure used on this material.
  38213. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38214. * This corresponds to a photographic exposure.
  38215. */
  38216. set: function (value) {
  38217. this._imageProcessingConfiguration.exposure = value;
  38218. },
  38219. enumerable: true,
  38220. configurable: true
  38221. });
  38222. ;
  38223. ;
  38224. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38225. /**
  38226. * Gets The camera contrast used on this material.
  38227. */
  38228. get: function () {
  38229. return this._imageProcessingConfiguration.contrast;
  38230. },
  38231. /**
  38232. * Sets The camera contrast used on this material.
  38233. */
  38234. set: function (value) {
  38235. this._imageProcessingConfiguration.contrast = value;
  38236. },
  38237. enumerable: true,
  38238. configurable: true
  38239. });
  38240. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38241. /**
  38242. * Gets the Color Grading 2D Lookup Texture.
  38243. */
  38244. get: function () {
  38245. return this._imageProcessingConfiguration.colorGradingTexture;
  38246. },
  38247. /**
  38248. * Sets the Color Grading 2D Lookup Texture.
  38249. */
  38250. set: function (value) {
  38251. this._imageProcessingConfiguration.colorGradingTexture = value;
  38252. },
  38253. enumerable: true,
  38254. configurable: true
  38255. });
  38256. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38257. /**
  38258. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38259. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38260. * 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;
  38261. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38262. */
  38263. get: function () {
  38264. return this._imageProcessingConfiguration.colorCurves;
  38265. },
  38266. /**
  38267. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38268. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38269. * 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;
  38270. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38271. */
  38272. set: function (value) {
  38273. this._imageProcessingConfiguration.colorCurves = value;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. PBRMaterial.prototype.getClassName = function () {
  38279. return "PBRMaterial";
  38280. };
  38281. PBRMaterial.prototype.getActiveTextures = function () {
  38282. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38283. if (this._albedoTexture) {
  38284. activeTextures.push(this._albedoTexture);
  38285. }
  38286. if (this._ambientTexture) {
  38287. activeTextures.push(this._ambientTexture);
  38288. }
  38289. if (this._opacityTexture) {
  38290. activeTextures.push(this._opacityTexture);
  38291. }
  38292. if (this._reflectionTexture) {
  38293. activeTextures.push(this._reflectionTexture);
  38294. }
  38295. if (this._emissiveTexture) {
  38296. activeTextures.push(this._emissiveTexture);
  38297. }
  38298. if (this._reflectivityTexture) {
  38299. activeTextures.push(this._reflectivityTexture);
  38300. }
  38301. if (this._metallicTexture) {
  38302. activeTextures.push(this._metallicTexture);
  38303. }
  38304. if (this._microSurfaceTexture) {
  38305. activeTextures.push(this._microSurfaceTexture);
  38306. }
  38307. if (this._bumpTexture) {
  38308. activeTextures.push(this._bumpTexture);
  38309. }
  38310. if (this._lightmapTexture) {
  38311. activeTextures.push(this._lightmapTexture);
  38312. }
  38313. if (this._refractionTexture) {
  38314. activeTextures.push(this._refractionTexture);
  38315. }
  38316. return activeTextures;
  38317. };
  38318. PBRMaterial.prototype.hasTexture = function (texture) {
  38319. if (_super.prototype.hasTexture.call(this, texture)) {
  38320. return true;
  38321. }
  38322. if (this._albedoTexture === texture) {
  38323. return true;
  38324. }
  38325. if (this._ambientTexture === texture) {
  38326. return true;
  38327. }
  38328. if (this._opacityTexture === texture) {
  38329. return true;
  38330. }
  38331. if (this._reflectionTexture === texture) {
  38332. return true;
  38333. }
  38334. if (this._reflectivityTexture === texture) {
  38335. return true;
  38336. }
  38337. if (this._metallicTexture === texture) {
  38338. return true;
  38339. }
  38340. if (this._microSurfaceTexture === texture) {
  38341. return true;
  38342. }
  38343. if (this._bumpTexture === texture) {
  38344. return true;
  38345. }
  38346. if (this._lightmapTexture === texture) {
  38347. return true;
  38348. }
  38349. if (this._refractionTexture === texture) {
  38350. return true;
  38351. }
  38352. return false;
  38353. };
  38354. PBRMaterial.prototype.clone = function (name) {
  38355. var _this = this;
  38356. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38357. clone.id = name;
  38358. clone.name = name;
  38359. return clone;
  38360. };
  38361. PBRMaterial.prototype.serialize = function () {
  38362. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38363. serializationObject.customType = "BABYLON.PBRMaterial";
  38364. return serializationObject;
  38365. };
  38366. // Statics
  38367. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38368. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38369. };
  38370. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38371. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38372. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38373. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38374. __decorate([
  38375. BABYLON.serialize(),
  38376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38377. ], PBRMaterial.prototype, "directIntensity", void 0);
  38378. __decorate([
  38379. BABYLON.serialize(),
  38380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38381. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38382. __decorate([
  38383. BABYLON.serialize(),
  38384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38385. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38386. __decorate([
  38387. BABYLON.serialize(),
  38388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38389. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38390. __decorate([
  38391. BABYLON.serialize(),
  38392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38393. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38394. __decorate([
  38395. BABYLON.serializeAsTexture(),
  38396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38397. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38398. __decorate([
  38399. BABYLON.serializeAsTexture(),
  38400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38401. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38402. __decorate([
  38403. BABYLON.serialize(),
  38404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38405. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38406. __decorate([
  38407. BABYLON.serializeAsTexture(),
  38408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38409. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38410. __decorate([
  38411. BABYLON.serializeAsTexture(),
  38412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38413. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38414. __decorate([
  38415. BABYLON.serializeAsTexture(),
  38416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38417. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38418. __decorate([
  38419. BABYLON.serializeAsTexture(),
  38420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38421. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38422. __decorate([
  38423. BABYLON.serializeAsTexture(),
  38424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38425. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38426. __decorate([
  38427. BABYLON.serialize(),
  38428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38429. ], PBRMaterial.prototype, "metallic", void 0);
  38430. __decorate([
  38431. BABYLON.serialize(),
  38432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38433. ], PBRMaterial.prototype, "roughness", void 0);
  38434. __decorate([
  38435. BABYLON.serializeAsTexture(),
  38436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38437. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38438. __decorate([
  38439. BABYLON.serializeAsTexture(),
  38440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38441. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38442. __decorate([
  38443. BABYLON.serializeAsTexture(),
  38444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38445. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38446. __decorate([
  38447. BABYLON.serializeAsTexture(),
  38448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38449. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38450. __decorate([
  38451. BABYLON.serializeAsColor3("ambient"),
  38452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38453. ], PBRMaterial.prototype, "ambientColor", void 0);
  38454. __decorate([
  38455. BABYLON.serializeAsColor3("albedo"),
  38456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38457. ], PBRMaterial.prototype, "albedoColor", void 0);
  38458. __decorate([
  38459. BABYLON.serializeAsColor3("reflectivity"),
  38460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38461. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38462. __decorate([
  38463. BABYLON.serializeAsColor3("reflection"),
  38464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38465. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38466. __decorate([
  38467. BABYLON.serializeAsColor3("emissive"),
  38468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38469. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38470. __decorate([
  38471. BABYLON.serialize(),
  38472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38473. ], PBRMaterial.prototype, "microSurface", void 0);
  38474. __decorate([
  38475. BABYLON.serialize(),
  38476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38477. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38478. __decorate([
  38479. BABYLON.serialize(),
  38480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38481. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38482. __decorate([
  38483. BABYLON.serialize(),
  38484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38485. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38486. __decorate([
  38487. BABYLON.serialize(),
  38488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38489. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38490. __decorate([
  38491. BABYLON.serialize(),
  38492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38493. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38494. __decorate([
  38495. BABYLON.serialize(),
  38496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38497. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38498. __decorate([
  38499. BABYLON.serialize(),
  38500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38501. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38502. __decorate([
  38503. BABYLON.serialize(),
  38504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38505. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38506. __decorate([
  38507. BABYLON.serialize(),
  38508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38509. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38510. __decorate([
  38511. BABYLON.serialize(),
  38512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38513. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38514. __decorate([
  38515. BABYLON.serialize(),
  38516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38517. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38518. __decorate([
  38519. BABYLON.serialize(),
  38520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38521. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38522. __decorate([
  38523. BABYLON.serialize(),
  38524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38525. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38526. __decorate([
  38527. BABYLON.serialize(),
  38528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38529. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38530. __decorate([
  38531. BABYLON.serialize(),
  38532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38533. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38534. __decorate([
  38535. BABYLON.serialize(),
  38536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38537. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38538. __decorate([
  38539. BABYLON.serialize(),
  38540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38541. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38542. __decorate([
  38543. BABYLON.serialize(),
  38544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38545. ], PBRMaterial.prototype, "useParallax", void 0);
  38546. __decorate([
  38547. BABYLON.serialize(),
  38548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38549. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38550. __decorate([
  38551. BABYLON.serialize(),
  38552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38553. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38554. __decorate([
  38555. BABYLON.serialize(),
  38556. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38557. ], PBRMaterial.prototype, "disableLighting", void 0);
  38558. __decorate([
  38559. BABYLON.serialize(),
  38560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38561. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38562. __decorate([
  38563. BABYLON.serialize(),
  38564. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38565. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38566. __decorate([
  38567. BABYLON.serialize(),
  38568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38569. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38570. __decorate([
  38571. BABYLON.serialize(),
  38572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38573. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38574. __decorate([
  38575. BABYLON.serialize(),
  38576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38577. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38578. __decorate([
  38579. BABYLON.serialize(),
  38580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38581. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38582. __decorate([
  38583. BABYLON.serialize(),
  38584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38585. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38586. __decorate([
  38587. BABYLON.serializeAsTexture(),
  38588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38589. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38590. __decorate([
  38591. BABYLON.serialize(),
  38592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38593. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38594. __decorate([
  38595. BABYLON.serialize(),
  38596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38597. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38598. __decorate([
  38599. BABYLON.serialize(),
  38600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38601. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38602. return PBRMaterial;
  38603. }(BABYLON.PBRBaseMaterial));
  38604. BABYLON.PBRMaterial = PBRMaterial;
  38605. })(BABYLON || (BABYLON = {}));
  38606. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38607. var BABYLON;
  38608. (function (BABYLON) {
  38609. /**
  38610. * The PBR material of BJS following the metal roughness convention.
  38611. *
  38612. * This fits to the PBR convention in the GLTF definition:
  38613. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38614. */
  38615. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38616. __extends(PBRMetallicRoughnessMaterial, _super);
  38617. /**
  38618. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38619. *
  38620. * @param name The material name
  38621. * @param scene The scene the material will be use in.
  38622. */
  38623. function PBRMetallicRoughnessMaterial(name, scene) {
  38624. var _this = _super.call(this, name, scene) || this;
  38625. _this._useRoughnessFromMetallicTextureAlpha = false;
  38626. _this._useRoughnessFromMetallicTextureGreen = true;
  38627. _this._useMetallnessFromMetallicTextureBlue = true;
  38628. _this._forceMetallicWorkflow = true;
  38629. return _this;
  38630. }
  38631. /**
  38632. * Return the currrent class name of the material.
  38633. */
  38634. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38635. return "PBRMetallicRoughnessMaterial";
  38636. };
  38637. /**
  38638. * Return the active textures of the material.
  38639. */
  38640. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38641. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38642. if (this.baseTexture) {
  38643. activeTextures.push(this.baseTexture);
  38644. }
  38645. if (this.metallicRoughnessTexture) {
  38646. activeTextures.push(this.metallicRoughnessTexture);
  38647. }
  38648. return activeTextures;
  38649. };
  38650. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38651. if (_super.prototype.hasTexture.call(this, texture)) {
  38652. return true;
  38653. }
  38654. if (this.baseTexture === texture) {
  38655. return true;
  38656. }
  38657. if (this.metallicRoughnessTexture === texture) {
  38658. return true;
  38659. }
  38660. return false;
  38661. };
  38662. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38663. var _this = this;
  38664. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38665. clone.id = name;
  38666. clone.name = name;
  38667. return clone;
  38668. };
  38669. /**
  38670. * Serialize the material to a parsable JSON object.
  38671. */
  38672. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38673. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38674. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38675. return serializationObject;
  38676. };
  38677. /**
  38678. * Parses a JSON object correponding to the serialize function.
  38679. */
  38680. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38681. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38682. };
  38683. __decorate([
  38684. BABYLON.serializeAsColor3(),
  38685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38686. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38687. __decorate([
  38688. BABYLON.serializeAsTexture(),
  38689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38690. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38691. __decorate([
  38692. BABYLON.serialize(),
  38693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38694. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38695. __decorate([
  38696. BABYLON.serialize(),
  38697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38698. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38699. __decorate([
  38700. BABYLON.serializeAsTexture(),
  38701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38702. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38703. return PBRMetallicRoughnessMaterial;
  38704. }(BABYLON.PBRBaseSimpleMaterial));
  38705. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38706. })(BABYLON || (BABYLON = {}));
  38707. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38708. var BABYLON;
  38709. (function (BABYLON) {
  38710. /**
  38711. * The PBR material of BJS following the specular glossiness convention.
  38712. *
  38713. * This fits to the PBR convention in the GLTF definition:
  38714. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38715. */
  38716. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38717. __extends(PBRSpecularGlossinessMaterial, _super);
  38718. /**
  38719. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38720. *
  38721. * @param name The material name
  38722. * @param scene The scene the material will be use in.
  38723. */
  38724. function PBRSpecularGlossinessMaterial(name, scene) {
  38725. var _this = _super.call(this, name, scene) || this;
  38726. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38727. return _this;
  38728. }
  38729. /**
  38730. * Return the currrent class name of the material.
  38731. */
  38732. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38733. return "PBRSpecularGlossinessMaterial";
  38734. };
  38735. /**
  38736. * Return the active textures of the material.
  38737. */
  38738. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38739. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38740. if (this.diffuseTexture) {
  38741. activeTextures.push(this.diffuseTexture);
  38742. }
  38743. if (this.specularGlossinessTexture) {
  38744. activeTextures.push(this.specularGlossinessTexture);
  38745. }
  38746. return activeTextures;
  38747. };
  38748. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38749. if (_super.prototype.hasTexture.call(this, texture)) {
  38750. return true;
  38751. }
  38752. if (this.diffuseTexture === texture) {
  38753. return true;
  38754. }
  38755. if (this.specularGlossinessTexture === texture) {
  38756. return true;
  38757. }
  38758. return false;
  38759. };
  38760. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38761. var _this = this;
  38762. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38763. clone.id = name;
  38764. clone.name = name;
  38765. return clone;
  38766. };
  38767. /**
  38768. * Serialize the material to a parsable JSON object.
  38769. */
  38770. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38772. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38773. return serializationObject;
  38774. };
  38775. /**
  38776. * Parses a JSON object correponding to the serialize function.
  38777. */
  38778. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38779. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38780. };
  38781. __decorate([
  38782. BABYLON.serializeAsColor3("diffuse"),
  38783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38784. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38785. __decorate([
  38786. BABYLON.serializeAsTexture(),
  38787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38788. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38789. __decorate([
  38790. BABYLON.serializeAsColor3("specular"),
  38791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38792. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38793. __decorate([
  38794. BABYLON.serialize(),
  38795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38796. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38797. __decorate([
  38798. BABYLON.serializeAsTexture(),
  38799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38800. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38801. return PBRSpecularGlossinessMaterial;
  38802. }(BABYLON.PBRBaseSimpleMaterial));
  38803. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38804. })(BABYLON || (BABYLON = {}));
  38805. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38806. var BABYLON;
  38807. (function (BABYLON) {
  38808. BABYLON.CameraInputTypes = {};
  38809. var CameraInputsManager = /** @class */ (function () {
  38810. function CameraInputsManager(camera) {
  38811. this.attached = {};
  38812. this.camera = camera;
  38813. this.checkInputs = function () { };
  38814. }
  38815. CameraInputsManager.prototype.add = function (input) {
  38816. var type = input.getSimpleName();
  38817. if (this.attached[type]) {
  38818. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38819. return;
  38820. }
  38821. this.attached[type] = input;
  38822. input.camera = this.camera;
  38823. //for checkInputs, we are dynamically creating a function
  38824. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38825. if (input.checkInputs) {
  38826. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38827. }
  38828. if (this.attachedElement) {
  38829. input.attachControl(this.attachedElement);
  38830. }
  38831. };
  38832. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38833. for (var cam in this.attached) {
  38834. var input = this.attached[cam];
  38835. if (input === inputToRemove) {
  38836. input.detachControl(this.attachedElement);
  38837. input.camera = null;
  38838. delete this.attached[cam];
  38839. this.rebuildInputCheck();
  38840. }
  38841. }
  38842. };
  38843. CameraInputsManager.prototype.removeByType = function (inputType) {
  38844. for (var cam in this.attached) {
  38845. var input = this.attached[cam];
  38846. if (input.getClassName() === inputType) {
  38847. input.detachControl(this.attachedElement);
  38848. input.camera = null;
  38849. delete this.attached[cam];
  38850. this.rebuildInputCheck();
  38851. }
  38852. }
  38853. };
  38854. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38855. var current = this.checkInputs;
  38856. return function () {
  38857. current();
  38858. fn();
  38859. };
  38860. };
  38861. CameraInputsManager.prototype.attachInput = function (input) {
  38862. if (this.attachedElement) {
  38863. input.attachControl(this.attachedElement, this.noPreventDefault);
  38864. }
  38865. };
  38866. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38867. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38868. if (this.attachedElement) {
  38869. return;
  38870. }
  38871. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38872. this.attachedElement = element;
  38873. this.noPreventDefault = noPreventDefault;
  38874. for (var cam in this.attached) {
  38875. this.attached[cam].attachControl(element, noPreventDefault);
  38876. }
  38877. };
  38878. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38879. if (disconnect === void 0) { disconnect = false; }
  38880. if (this.attachedElement !== element) {
  38881. return;
  38882. }
  38883. for (var cam in this.attached) {
  38884. this.attached[cam].detachControl(element);
  38885. if (disconnect) {
  38886. this.attached[cam].camera = null;
  38887. }
  38888. }
  38889. this.attachedElement = null;
  38890. };
  38891. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38892. this.checkInputs = function () { };
  38893. for (var cam in this.attached) {
  38894. var input = this.attached[cam];
  38895. if (input.checkInputs) {
  38896. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38897. }
  38898. }
  38899. };
  38900. CameraInputsManager.prototype.clear = function () {
  38901. if (this.attachedElement) {
  38902. this.detachElement(this.attachedElement, true);
  38903. }
  38904. this.attached = {};
  38905. this.attachedElement = null;
  38906. this.checkInputs = function () { };
  38907. };
  38908. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38909. var inputs = {};
  38910. for (var cam in this.attached) {
  38911. var input = this.attached[cam];
  38912. var res = BABYLON.SerializationHelper.Serialize(input);
  38913. inputs[input.getClassName()] = res;
  38914. }
  38915. serializedCamera.inputsmgr = inputs;
  38916. };
  38917. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38918. var parsedInputs = parsedCamera.inputsmgr;
  38919. if (parsedInputs) {
  38920. this.clear();
  38921. for (var n in parsedInputs) {
  38922. var construct = BABYLON.CameraInputTypes[n];
  38923. if (construct) {
  38924. var parsedinput = parsedInputs[n];
  38925. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38926. this.add(input);
  38927. }
  38928. }
  38929. }
  38930. else {
  38931. //2016-03-08 this part is for managing backward compatibility
  38932. for (var n in this.attached) {
  38933. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38934. if (construct) {
  38935. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38936. this.remove(this.attached[n]);
  38937. this.add(input);
  38938. }
  38939. }
  38940. }
  38941. };
  38942. return CameraInputsManager;
  38943. }());
  38944. BABYLON.CameraInputsManager = CameraInputsManager;
  38945. })(BABYLON || (BABYLON = {}));
  38946. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38947. var BABYLON;
  38948. (function (BABYLON) {
  38949. var TargetCamera = /** @class */ (function (_super) {
  38950. __extends(TargetCamera, _super);
  38951. function TargetCamera(name, position, scene) {
  38952. var _this = _super.call(this, name, position, scene) || this;
  38953. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38954. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38955. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38956. _this.speed = 2.0;
  38957. _this.noRotationConstraint = false;
  38958. _this.lockedTarget = null;
  38959. _this._currentTarget = BABYLON.Vector3.Zero();
  38960. _this._viewMatrix = BABYLON.Matrix.Zero();
  38961. _this._camMatrix = BABYLON.Matrix.Zero();
  38962. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38963. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38964. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38965. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38966. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38967. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38968. _this._tempMatrix = BABYLON.Matrix.Zero();
  38969. return _this;
  38970. }
  38971. TargetCamera.prototype.getFrontPosition = function (distance) {
  38972. this.getWorldMatrix();
  38973. var direction = this.getTarget().subtract(this.position);
  38974. direction.normalize();
  38975. direction.scaleInPlace(distance);
  38976. return this.globalPosition.add(direction);
  38977. };
  38978. TargetCamera.prototype._getLockedTargetPosition = function () {
  38979. if (!this.lockedTarget) {
  38980. return null;
  38981. }
  38982. if (this.lockedTarget.absolutePosition) {
  38983. this.lockedTarget.computeWorldMatrix();
  38984. }
  38985. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38986. };
  38987. TargetCamera.prototype.storeState = function () {
  38988. this._storedPosition = this.position.clone();
  38989. this._storedRotation = this.rotation.clone();
  38990. if (this.rotationQuaternion) {
  38991. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38992. }
  38993. return _super.prototype.storeState.call(this);
  38994. };
  38995. /**
  38996. * Restored camera state. You must call storeState() first
  38997. */
  38998. TargetCamera.prototype._restoreStateValues = function () {
  38999. if (!_super.prototype._restoreStateValues.call(this)) {
  39000. return false;
  39001. }
  39002. this.position = this._storedPosition.clone();
  39003. this.rotation = this._storedRotation.clone();
  39004. if (this.rotationQuaternion) {
  39005. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39006. }
  39007. this.cameraDirection.copyFromFloats(0, 0, 0);
  39008. this.cameraRotation.copyFromFloats(0, 0);
  39009. return true;
  39010. };
  39011. // Cache
  39012. TargetCamera.prototype._initCache = function () {
  39013. _super.prototype._initCache.call(this);
  39014. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39015. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39016. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39017. };
  39018. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39019. if (!ignoreParentClass) {
  39020. _super.prototype._updateCache.call(this);
  39021. }
  39022. var lockedTargetPosition = this._getLockedTargetPosition();
  39023. if (!lockedTargetPosition) {
  39024. this._cache.lockedTarget = null;
  39025. }
  39026. else {
  39027. if (!this._cache.lockedTarget) {
  39028. this._cache.lockedTarget = lockedTargetPosition.clone();
  39029. }
  39030. else {
  39031. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39032. }
  39033. }
  39034. this._cache.rotation.copyFrom(this.rotation);
  39035. if (this.rotationQuaternion)
  39036. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39037. };
  39038. // Synchronized
  39039. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39040. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39041. return false;
  39042. }
  39043. var lockedTargetPosition = this._getLockedTargetPosition();
  39044. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39045. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39046. };
  39047. // Methods
  39048. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39049. var engine = this.getEngine();
  39050. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39051. };
  39052. // Target
  39053. TargetCamera.prototype.setTarget = function (target) {
  39054. this.upVector.normalize();
  39055. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39056. this._camMatrix.invert();
  39057. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39058. var vDir = target.subtract(this.position);
  39059. if (vDir.x >= 0.0) {
  39060. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39061. }
  39062. else {
  39063. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39064. }
  39065. this.rotation.z = 0;
  39066. if (isNaN(this.rotation.x)) {
  39067. this.rotation.x = 0;
  39068. }
  39069. if (isNaN(this.rotation.y)) {
  39070. this.rotation.y = 0;
  39071. }
  39072. if (isNaN(this.rotation.z)) {
  39073. this.rotation.z = 0;
  39074. }
  39075. if (this.rotationQuaternion) {
  39076. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39077. }
  39078. };
  39079. /**
  39080. * Return the current target position of the camera. This value is expressed in local space.
  39081. */
  39082. TargetCamera.prototype.getTarget = function () {
  39083. return this._currentTarget;
  39084. };
  39085. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39086. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39087. };
  39088. TargetCamera.prototype._updatePosition = function () {
  39089. if (this.parent) {
  39090. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39091. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39092. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39093. return;
  39094. }
  39095. this.position.addInPlace(this.cameraDirection);
  39096. };
  39097. TargetCamera.prototype._checkInputs = function () {
  39098. var needToMove = this._decideIfNeedsToMove();
  39099. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39100. // Move
  39101. if (needToMove) {
  39102. this._updatePosition();
  39103. }
  39104. // Rotate
  39105. if (needToRotate) {
  39106. this.rotation.x += this.cameraRotation.x;
  39107. this.rotation.y += this.cameraRotation.y;
  39108. //rotate, if quaternion is set and rotation was used
  39109. if (this.rotationQuaternion) {
  39110. var len = this.rotation.lengthSquared();
  39111. if (len) {
  39112. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39113. }
  39114. }
  39115. if (!this.noRotationConstraint) {
  39116. var limit = (Math.PI / 2) * 0.95;
  39117. if (this.rotation.x > limit)
  39118. this.rotation.x = limit;
  39119. if (this.rotation.x < -limit)
  39120. this.rotation.x = -limit;
  39121. }
  39122. }
  39123. // Inertia
  39124. if (needToMove) {
  39125. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39126. this.cameraDirection.x = 0;
  39127. }
  39128. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39129. this.cameraDirection.y = 0;
  39130. }
  39131. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39132. this.cameraDirection.z = 0;
  39133. }
  39134. this.cameraDirection.scaleInPlace(this.inertia);
  39135. }
  39136. if (needToRotate) {
  39137. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39138. this.cameraRotation.x = 0;
  39139. }
  39140. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39141. this.cameraRotation.y = 0;
  39142. }
  39143. this.cameraRotation.scaleInPlace(this.inertia);
  39144. }
  39145. _super.prototype._checkInputs.call(this);
  39146. };
  39147. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39148. if (this.rotationQuaternion) {
  39149. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39150. }
  39151. else {
  39152. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39153. }
  39154. //update the up vector!
  39155. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39156. };
  39157. TargetCamera.prototype._getViewMatrix = function () {
  39158. if (this.lockedTarget) {
  39159. this.setTarget(this._getLockedTargetPosition());
  39160. }
  39161. // Compute
  39162. this._updateCameraRotationMatrix();
  39163. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39164. // Computing target and final matrix
  39165. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39166. if (this.getScene().useRightHandedSystem) {
  39167. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39168. }
  39169. else {
  39170. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39171. }
  39172. return this._viewMatrix;
  39173. };
  39174. /**
  39175. * @override
  39176. * Override Camera.createRigCamera
  39177. */
  39178. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39179. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39180. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39181. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39182. if (!this.rotationQuaternion) {
  39183. this.rotationQuaternion = new BABYLON.Quaternion();
  39184. }
  39185. rigCamera._cameraRigParams = {};
  39186. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39187. }
  39188. return rigCamera;
  39189. }
  39190. return null;
  39191. };
  39192. /**
  39193. * @override
  39194. * Override Camera._updateRigCameras
  39195. */
  39196. TargetCamera.prototype._updateRigCameras = function () {
  39197. var camLeft = this._rigCameras[0];
  39198. var camRight = this._rigCameras[1];
  39199. switch (this.cameraRigMode) {
  39200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39201. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39202. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39204. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39205. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39206. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39207. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39208. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39209. camLeft.setTarget(this.getTarget());
  39210. camRight.setTarget(this.getTarget());
  39211. break;
  39212. case BABYLON.Camera.RIG_MODE_VR:
  39213. if (camLeft.rotationQuaternion) {
  39214. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39215. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39216. }
  39217. else {
  39218. camLeft.rotation.copyFrom(this.rotation);
  39219. camRight.rotation.copyFrom(this.rotation);
  39220. }
  39221. camLeft.position.copyFrom(this.position);
  39222. camRight.position.copyFrom(this.position);
  39223. break;
  39224. }
  39225. _super.prototype._updateRigCameras.call(this);
  39226. };
  39227. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39228. if (!this._rigCamTransformMatrix) {
  39229. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39230. }
  39231. var target = this.getTarget();
  39232. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39233. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39234. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39235. };
  39236. TargetCamera.prototype.getClassName = function () {
  39237. return "TargetCamera";
  39238. };
  39239. __decorate([
  39240. BABYLON.serializeAsVector3()
  39241. ], TargetCamera.prototype, "rotation", void 0);
  39242. __decorate([
  39243. BABYLON.serialize()
  39244. ], TargetCamera.prototype, "speed", void 0);
  39245. __decorate([
  39246. BABYLON.serializeAsMeshReference("lockedTargetId")
  39247. ], TargetCamera.prototype, "lockedTarget", void 0);
  39248. return TargetCamera;
  39249. }(BABYLON.Camera));
  39250. BABYLON.TargetCamera = TargetCamera;
  39251. })(BABYLON || (BABYLON = {}));
  39252. //# sourceMappingURL=babylon.targetCamera.js.map
  39253. var BABYLON;
  39254. (function (BABYLON) {
  39255. var FreeCameraMouseInput = /** @class */ (function () {
  39256. function FreeCameraMouseInput(touchEnabled) {
  39257. if (touchEnabled === void 0) { touchEnabled = true; }
  39258. this.touchEnabled = touchEnabled;
  39259. this.buttons = [0, 1, 2];
  39260. this.angularSensibility = 2000.0;
  39261. this.previousPosition = null;
  39262. }
  39263. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39264. var _this = this;
  39265. var engine = this.camera.getEngine();
  39266. if (!this._pointerInput) {
  39267. this._pointerInput = function (p, s) {
  39268. var evt = p.event;
  39269. if (engine.isInVRExclusivePointerMode) {
  39270. return;
  39271. }
  39272. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39273. return;
  39274. }
  39275. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39276. return;
  39277. }
  39278. var srcElement = (evt.srcElement || evt.target);
  39279. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39280. try {
  39281. srcElement.setPointerCapture(evt.pointerId);
  39282. }
  39283. catch (e) {
  39284. //Nothing to do with the error. Execution will continue.
  39285. }
  39286. _this.previousPosition = {
  39287. x: evt.clientX,
  39288. y: evt.clientY
  39289. };
  39290. if (!noPreventDefault) {
  39291. evt.preventDefault();
  39292. element.focus();
  39293. }
  39294. }
  39295. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39296. try {
  39297. srcElement.releasePointerCapture(evt.pointerId);
  39298. }
  39299. catch (e) {
  39300. //Nothing to do with the error.
  39301. }
  39302. _this.previousPosition = null;
  39303. if (!noPreventDefault) {
  39304. evt.preventDefault();
  39305. }
  39306. }
  39307. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39308. if (!_this.previousPosition || engine.isPointerLock) {
  39309. return;
  39310. }
  39311. var offsetX = evt.clientX - _this.previousPosition.x;
  39312. var offsetY = evt.clientY - _this.previousPosition.y;
  39313. if (_this.camera.getScene().useRightHandedSystem) {
  39314. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39315. }
  39316. else {
  39317. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39318. }
  39319. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39320. _this.previousPosition = {
  39321. x: evt.clientX,
  39322. y: evt.clientY
  39323. };
  39324. if (!noPreventDefault) {
  39325. evt.preventDefault();
  39326. }
  39327. }
  39328. };
  39329. }
  39330. this._onMouseMove = function (evt) {
  39331. if (!engine.isPointerLock) {
  39332. return;
  39333. }
  39334. if (engine.isInVRExclusivePointerMode) {
  39335. return;
  39336. }
  39337. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39338. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39339. if (_this.camera.getScene().useRightHandedSystem) {
  39340. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39341. }
  39342. else {
  39343. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39344. }
  39345. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39346. _this.previousPosition = null;
  39347. if (!noPreventDefault) {
  39348. evt.preventDefault();
  39349. }
  39350. };
  39351. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39352. element.addEventListener("mousemove", this._onMouseMove, false);
  39353. };
  39354. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39355. if (this._observer && element) {
  39356. this.camera.getScene().onPointerObservable.remove(this._observer);
  39357. if (this._onMouseMove) {
  39358. element.removeEventListener("mousemove", this._onMouseMove);
  39359. }
  39360. this._observer = null;
  39361. this._onMouseMove = null;
  39362. this.previousPosition = null;
  39363. }
  39364. };
  39365. FreeCameraMouseInput.prototype.getClassName = function () {
  39366. return "FreeCameraMouseInput";
  39367. };
  39368. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39369. return "mouse";
  39370. };
  39371. __decorate([
  39372. BABYLON.serialize()
  39373. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39374. __decorate([
  39375. BABYLON.serialize()
  39376. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39377. return FreeCameraMouseInput;
  39378. }());
  39379. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39380. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39381. })(BABYLON || (BABYLON = {}));
  39382. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39383. var BABYLON;
  39384. (function (BABYLON) {
  39385. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39386. function FreeCameraKeyboardMoveInput() {
  39387. this._keys = new Array();
  39388. this.keysUp = [38];
  39389. this.keysDown = [40];
  39390. this.keysLeft = [37];
  39391. this.keysRight = [39];
  39392. }
  39393. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39394. var _this = this;
  39395. if (this._onCanvasBlurObserver) {
  39396. return;
  39397. }
  39398. this._scene = this.camera.getScene();
  39399. this._engine = this._scene.getEngine();
  39400. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39401. _this._keys = [];
  39402. });
  39403. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39404. var evt = info.event;
  39405. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39406. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39407. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39408. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39409. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39410. var index = _this._keys.indexOf(evt.keyCode);
  39411. if (index === -1) {
  39412. _this._keys.push(evt.keyCode);
  39413. }
  39414. if (!noPreventDefault) {
  39415. evt.preventDefault();
  39416. }
  39417. }
  39418. }
  39419. else {
  39420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39423. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39424. var index = _this._keys.indexOf(evt.keyCode);
  39425. if (index >= 0) {
  39426. _this._keys.splice(index, 1);
  39427. }
  39428. if (!noPreventDefault) {
  39429. evt.preventDefault();
  39430. }
  39431. }
  39432. }
  39433. });
  39434. };
  39435. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39436. if (this._scene) {
  39437. if (this._onKeyboardObserver) {
  39438. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39439. }
  39440. if (this._onCanvasBlurObserver) {
  39441. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39442. }
  39443. this._onKeyboardObserver = null;
  39444. this._onCanvasBlurObserver = null;
  39445. }
  39446. this._keys = [];
  39447. };
  39448. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39449. if (this._onKeyboardObserver) {
  39450. var camera = this.camera;
  39451. // Keyboard
  39452. for (var index = 0; index < this._keys.length; index++) {
  39453. var keyCode = this._keys[index];
  39454. var speed = camera._computeLocalCameraSpeed();
  39455. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39456. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39457. }
  39458. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39459. camera._localDirection.copyFromFloats(0, 0, speed);
  39460. }
  39461. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39462. camera._localDirection.copyFromFloats(speed, 0, 0);
  39463. }
  39464. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39465. camera._localDirection.copyFromFloats(0, 0, -speed);
  39466. }
  39467. if (camera.getScene().useRightHandedSystem) {
  39468. camera._localDirection.z *= -1;
  39469. }
  39470. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39471. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39472. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39473. }
  39474. }
  39475. };
  39476. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39477. return "FreeCameraKeyboardMoveInput";
  39478. };
  39479. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39480. this._keys = [];
  39481. };
  39482. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39483. return "keyboard";
  39484. };
  39485. __decorate([
  39486. BABYLON.serialize()
  39487. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39488. __decorate([
  39489. BABYLON.serialize()
  39490. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39491. __decorate([
  39492. BABYLON.serialize()
  39493. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39494. __decorate([
  39495. BABYLON.serialize()
  39496. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39497. return FreeCameraKeyboardMoveInput;
  39498. }());
  39499. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39500. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39501. })(BABYLON || (BABYLON = {}));
  39502. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39503. var BABYLON;
  39504. (function (BABYLON) {
  39505. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39506. __extends(FreeCameraInputsManager, _super);
  39507. function FreeCameraInputsManager(camera) {
  39508. return _super.call(this, camera) || this;
  39509. }
  39510. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39511. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39512. return this;
  39513. };
  39514. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39515. if (touchEnabled === void 0) { touchEnabled = true; }
  39516. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39517. return this;
  39518. };
  39519. FreeCameraInputsManager.prototype.addGamepad = function () {
  39520. this.add(new BABYLON.FreeCameraGamepadInput());
  39521. return this;
  39522. };
  39523. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39524. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39525. return this;
  39526. };
  39527. FreeCameraInputsManager.prototype.addTouch = function () {
  39528. this.add(new BABYLON.FreeCameraTouchInput());
  39529. return this;
  39530. };
  39531. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39532. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39533. return this;
  39534. };
  39535. return FreeCameraInputsManager;
  39536. }(BABYLON.CameraInputsManager));
  39537. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39538. })(BABYLON || (BABYLON = {}));
  39539. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39540. var BABYLON;
  39541. (function (BABYLON) {
  39542. var FreeCamera = /** @class */ (function (_super) {
  39543. __extends(FreeCamera, _super);
  39544. function FreeCamera(name, position, scene) {
  39545. var _this = _super.call(this, name, position, scene) || this;
  39546. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39547. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39548. _this.checkCollisions = false;
  39549. _this.applyGravity = false;
  39550. _this._needMoveForGravity = false;
  39551. _this._oldPosition = BABYLON.Vector3.Zero();
  39552. _this._diffPosition = BABYLON.Vector3.Zero();
  39553. _this._newPosition = BABYLON.Vector3.Zero();
  39554. // Collisions
  39555. _this._collisionMask = -1;
  39556. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39557. if (collidedMesh === void 0) { collidedMesh = null; }
  39558. //TODO move this to the collision coordinator!
  39559. if (_this.getScene().workerCollisions)
  39560. newPosition.multiplyInPlace(_this._collider._radius);
  39561. var updatePosition = function (newPos) {
  39562. _this._newPosition.copyFrom(newPos);
  39563. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39564. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39565. _this.position.addInPlace(_this._diffPosition);
  39566. if (_this.onCollide && collidedMesh) {
  39567. _this.onCollide(collidedMesh);
  39568. }
  39569. }
  39570. };
  39571. updatePosition(newPosition);
  39572. };
  39573. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39574. _this.inputs.addKeyboard().addMouse();
  39575. return _this;
  39576. }
  39577. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39578. //-- begin properties for backward compatibility for inputs
  39579. get: function () {
  39580. var mouse = this.inputs.attached["mouse"];
  39581. if (mouse)
  39582. return mouse.angularSensibility;
  39583. return 0;
  39584. },
  39585. set: function (value) {
  39586. var mouse = this.inputs.attached["mouse"];
  39587. if (mouse)
  39588. mouse.angularSensibility = value;
  39589. },
  39590. enumerable: true,
  39591. configurable: true
  39592. });
  39593. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39594. get: function () {
  39595. var keyboard = this.inputs.attached["keyboard"];
  39596. if (keyboard)
  39597. return keyboard.keysUp;
  39598. return [];
  39599. },
  39600. set: function (value) {
  39601. var keyboard = this.inputs.attached["keyboard"];
  39602. if (keyboard)
  39603. keyboard.keysUp = value;
  39604. },
  39605. enumerable: true,
  39606. configurable: true
  39607. });
  39608. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39609. get: function () {
  39610. var keyboard = this.inputs.attached["keyboard"];
  39611. if (keyboard)
  39612. return keyboard.keysDown;
  39613. return [];
  39614. },
  39615. set: function (value) {
  39616. var keyboard = this.inputs.attached["keyboard"];
  39617. if (keyboard)
  39618. keyboard.keysDown = value;
  39619. },
  39620. enumerable: true,
  39621. configurable: true
  39622. });
  39623. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39624. get: function () {
  39625. var keyboard = this.inputs.attached["keyboard"];
  39626. if (keyboard)
  39627. return keyboard.keysLeft;
  39628. return [];
  39629. },
  39630. set: function (value) {
  39631. var keyboard = this.inputs.attached["keyboard"];
  39632. if (keyboard)
  39633. keyboard.keysLeft = value;
  39634. },
  39635. enumerable: true,
  39636. configurable: true
  39637. });
  39638. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39639. get: function () {
  39640. var keyboard = this.inputs.attached["keyboard"];
  39641. if (keyboard)
  39642. return keyboard.keysRight;
  39643. return [];
  39644. },
  39645. set: function (value) {
  39646. var keyboard = this.inputs.attached["keyboard"];
  39647. if (keyboard)
  39648. keyboard.keysRight = value;
  39649. },
  39650. enumerable: true,
  39651. configurable: true
  39652. });
  39653. // Controls
  39654. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39655. this.inputs.attachElement(element, noPreventDefault);
  39656. };
  39657. FreeCamera.prototype.detachControl = function (element) {
  39658. this.inputs.detachElement(element);
  39659. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39660. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39661. };
  39662. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39663. get: function () {
  39664. return this._collisionMask;
  39665. },
  39666. set: function (mask) {
  39667. this._collisionMask = !isNaN(mask) ? mask : -1;
  39668. },
  39669. enumerable: true,
  39670. configurable: true
  39671. });
  39672. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39673. var globalPosition;
  39674. if (this.parent) {
  39675. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39676. }
  39677. else {
  39678. globalPosition = this.position;
  39679. }
  39680. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39681. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39682. if (!this._collider) {
  39683. this._collider = new BABYLON.Collider();
  39684. }
  39685. this._collider._radius = this.ellipsoid;
  39686. this._collider.collisionMask = this._collisionMask;
  39687. //no need for clone, as long as gravity is not on.
  39688. var actualDisplacement = displacement;
  39689. //add gravity to the direction to prevent the dual-collision checking
  39690. if (this.applyGravity) {
  39691. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39692. actualDisplacement = displacement.add(this.getScene().gravity);
  39693. }
  39694. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39695. };
  39696. FreeCamera.prototype._checkInputs = function () {
  39697. if (!this._localDirection) {
  39698. this._localDirection = BABYLON.Vector3.Zero();
  39699. this._transformedDirection = BABYLON.Vector3.Zero();
  39700. }
  39701. this.inputs.checkInputs();
  39702. _super.prototype._checkInputs.call(this);
  39703. };
  39704. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39705. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39706. };
  39707. FreeCamera.prototype._updatePosition = function () {
  39708. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39709. this._collideWithWorld(this.cameraDirection);
  39710. }
  39711. else {
  39712. _super.prototype._updatePosition.call(this);
  39713. }
  39714. };
  39715. FreeCamera.prototype.dispose = function () {
  39716. this.inputs.clear();
  39717. _super.prototype.dispose.call(this);
  39718. };
  39719. FreeCamera.prototype.getClassName = function () {
  39720. return "FreeCamera";
  39721. };
  39722. __decorate([
  39723. BABYLON.serializeAsVector3()
  39724. ], FreeCamera.prototype, "ellipsoid", void 0);
  39725. __decorate([
  39726. BABYLON.serializeAsVector3()
  39727. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39728. __decorate([
  39729. BABYLON.serialize()
  39730. ], FreeCamera.prototype, "checkCollisions", void 0);
  39731. __decorate([
  39732. BABYLON.serialize()
  39733. ], FreeCamera.prototype, "applyGravity", void 0);
  39734. return FreeCamera;
  39735. }(BABYLON.TargetCamera));
  39736. BABYLON.FreeCamera = FreeCamera;
  39737. })(BABYLON || (BABYLON = {}));
  39738. //# sourceMappingURL=babylon.freeCamera.js.map
  39739. var BABYLON;
  39740. (function (BABYLON) {
  39741. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39742. function ArcRotateCameraKeyboardMoveInput() {
  39743. this._keys = new Array();
  39744. this.keysUp = [38];
  39745. this.keysDown = [40];
  39746. this.keysLeft = [37];
  39747. this.keysRight = [39];
  39748. this.keysReset = [220];
  39749. this.panningSensibility = 50.0;
  39750. this.zoomingSensibility = 25.0;
  39751. this.useAltToZoom = true;
  39752. }
  39753. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39754. var _this = this;
  39755. if (this._onCanvasBlurObserver) {
  39756. return;
  39757. }
  39758. this._scene = this.camera.getScene();
  39759. this._engine = this._scene.getEngine();
  39760. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39761. _this._keys = [];
  39762. });
  39763. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39764. var evt = info.event;
  39765. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39766. _this._ctrlPressed = evt.ctrlKey;
  39767. _this._altPressed = evt.altKey;
  39768. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39769. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39770. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39771. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39772. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39773. var index = _this._keys.indexOf(evt.keyCode);
  39774. if (index === -1) {
  39775. _this._keys.push(evt.keyCode);
  39776. }
  39777. if (evt.preventDefault) {
  39778. if (!noPreventDefault) {
  39779. evt.preventDefault();
  39780. }
  39781. }
  39782. }
  39783. }
  39784. else {
  39785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39788. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39789. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39790. var index = _this._keys.indexOf(evt.keyCode);
  39791. if (index >= 0) {
  39792. _this._keys.splice(index, 1);
  39793. }
  39794. if (evt.preventDefault) {
  39795. if (!noPreventDefault) {
  39796. evt.preventDefault();
  39797. }
  39798. }
  39799. }
  39800. }
  39801. });
  39802. };
  39803. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39804. if (this._scene) {
  39805. if (this._onKeyboardObserver) {
  39806. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39807. }
  39808. if (this._onCanvasBlurObserver) {
  39809. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39810. }
  39811. this._onKeyboardObserver = null;
  39812. this._onCanvasBlurObserver = null;
  39813. }
  39814. this._keys = [];
  39815. };
  39816. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39817. if (this._onKeyboardObserver) {
  39818. var camera = this.camera;
  39819. for (var index = 0; index < this._keys.length; index++) {
  39820. var keyCode = this._keys[index];
  39821. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39822. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39823. camera.inertialPanningX -= 1 / this.panningSensibility;
  39824. }
  39825. else {
  39826. camera.inertialAlphaOffset -= 0.01;
  39827. }
  39828. }
  39829. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39830. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39831. camera.inertialPanningY += 1 / this.panningSensibility;
  39832. }
  39833. else if (this._altPressed && this.useAltToZoom) {
  39834. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39835. }
  39836. else {
  39837. camera.inertialBetaOffset -= 0.01;
  39838. }
  39839. }
  39840. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39841. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39842. camera.inertialPanningX += 1 / this.panningSensibility;
  39843. }
  39844. else {
  39845. camera.inertialAlphaOffset += 0.01;
  39846. }
  39847. }
  39848. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39849. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39850. camera.inertialPanningY -= 1 / this.panningSensibility;
  39851. }
  39852. else if (this._altPressed && this.useAltToZoom) {
  39853. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39854. }
  39855. else {
  39856. camera.inertialBetaOffset += 0.01;
  39857. }
  39858. }
  39859. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39860. camera.restoreState();
  39861. }
  39862. }
  39863. }
  39864. };
  39865. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39866. return "ArcRotateCameraKeyboardMoveInput";
  39867. };
  39868. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39869. return "keyboard";
  39870. };
  39871. __decorate([
  39872. BABYLON.serialize()
  39873. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39874. __decorate([
  39875. BABYLON.serialize()
  39876. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39877. __decorate([
  39878. BABYLON.serialize()
  39879. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39880. __decorate([
  39881. BABYLON.serialize()
  39882. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39883. __decorate([
  39884. BABYLON.serialize()
  39885. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39886. __decorate([
  39887. BABYLON.serialize()
  39888. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39889. __decorate([
  39890. BABYLON.serialize()
  39891. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39892. __decorate([
  39893. BABYLON.serialize()
  39894. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39895. return ArcRotateCameraKeyboardMoveInput;
  39896. }());
  39897. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39898. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39899. })(BABYLON || (BABYLON = {}));
  39900. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39901. var BABYLON;
  39902. (function (BABYLON) {
  39903. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39904. function ArcRotateCameraMouseWheelInput() {
  39905. this.wheelPrecision = 3.0;
  39906. /**
  39907. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39908. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39909. */
  39910. this.wheelDeltaPercentage = 0;
  39911. }
  39912. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39913. var _this = this;
  39914. this._wheel = function (p, s) {
  39915. //sanity check - this should be a PointerWheel event.
  39916. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39917. return;
  39918. var event = p.event;
  39919. var delta = 0;
  39920. if (event.wheelDelta) {
  39921. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39922. }
  39923. else if (event.detail) {
  39924. delta = -event.detail / _this.wheelPrecision;
  39925. }
  39926. if (delta)
  39927. _this.camera.inertialRadiusOffset += delta;
  39928. if (event.preventDefault) {
  39929. if (!noPreventDefault) {
  39930. event.preventDefault();
  39931. }
  39932. }
  39933. };
  39934. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39935. };
  39936. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39937. if (this._observer && element) {
  39938. this.camera.getScene().onPointerObservable.remove(this._observer);
  39939. this._observer = null;
  39940. this._wheel = null;
  39941. }
  39942. };
  39943. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39944. return "ArcRotateCameraMouseWheelInput";
  39945. };
  39946. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39947. return "mousewheel";
  39948. };
  39949. __decorate([
  39950. BABYLON.serialize()
  39951. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39952. __decorate([
  39953. BABYLON.serialize()
  39954. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39955. return ArcRotateCameraMouseWheelInput;
  39956. }());
  39957. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39958. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39959. })(BABYLON || (BABYLON = {}));
  39960. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39961. var BABYLON;
  39962. (function (BABYLON) {
  39963. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39964. function ArcRotateCameraPointersInput() {
  39965. this.buttons = [0, 1, 2];
  39966. this.angularSensibilityX = 1000.0;
  39967. this.angularSensibilityY = 1000.0;
  39968. this.pinchPrecision = 12.0;
  39969. /**
  39970. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39971. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39972. */
  39973. this.pinchDeltaPercentage = 0;
  39974. this.panningSensibility = 1000.0;
  39975. this.multiTouchPanning = true;
  39976. this.multiTouchPanAndZoom = true;
  39977. this._isPanClick = false;
  39978. this.pinchInwards = true;
  39979. }
  39980. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39981. var _this = this;
  39982. var engine = this.camera.getEngine();
  39983. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39984. var pointA = null;
  39985. var pointB = null;
  39986. var previousPinchSquaredDistance = 0;
  39987. var initialDistance = 0;
  39988. var twoFingerActivityCount = 0;
  39989. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39990. this._pointerInput = function (p, s) {
  39991. var evt = p.event;
  39992. var isTouch = p.event.pointerType === "touch";
  39993. if (engine.isInVRExclusivePointerMode) {
  39994. return;
  39995. }
  39996. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39997. return;
  39998. }
  39999. var srcElement = (evt.srcElement || evt.target);
  40000. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40001. try {
  40002. srcElement.setPointerCapture(evt.pointerId);
  40003. }
  40004. catch (e) {
  40005. //Nothing to do with the error. Execution will continue.
  40006. }
  40007. // Manage panning with pan button click
  40008. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40009. // manage pointers
  40010. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40011. if (pointA === null) {
  40012. pointA = cacheSoloPointer;
  40013. }
  40014. else if (pointB === null) {
  40015. pointB = cacheSoloPointer;
  40016. }
  40017. if (!noPreventDefault) {
  40018. evt.preventDefault();
  40019. element.focus();
  40020. }
  40021. }
  40022. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40023. _this.camera.restoreState();
  40024. }
  40025. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40026. try {
  40027. srcElement.releasePointerCapture(evt.pointerId);
  40028. }
  40029. catch (e) {
  40030. //Nothing to do with the error.
  40031. }
  40032. cacheSoloPointer = null;
  40033. previousPinchSquaredDistance = 0;
  40034. previousMultiTouchPanPosition.isPaning = false;
  40035. previousMultiTouchPanPosition.isPinching = false;
  40036. twoFingerActivityCount = 0;
  40037. initialDistance = 0;
  40038. if (!isTouch) {
  40039. pointB = null; // Mouse and pen are mono pointer
  40040. }
  40041. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40042. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40043. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40044. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40045. if (engine.badOS) {
  40046. pointA = pointB = null;
  40047. }
  40048. else {
  40049. //only remove the impacted pointer in case of multitouch allowing on most
  40050. //platforms switching from rotate to zoom and pan seamlessly.
  40051. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40052. pointA = pointB;
  40053. pointB = null;
  40054. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40055. }
  40056. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40057. pointB = null;
  40058. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40059. }
  40060. else {
  40061. pointA = pointB = null;
  40062. }
  40063. }
  40064. if (!noPreventDefault) {
  40065. evt.preventDefault();
  40066. }
  40067. }
  40068. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40069. if (!noPreventDefault) {
  40070. evt.preventDefault();
  40071. }
  40072. // One button down
  40073. if (pointA && pointB === null && cacheSoloPointer) {
  40074. if (_this.panningSensibility !== 0 &&
  40075. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40076. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40077. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40078. }
  40079. else {
  40080. var offsetX = evt.clientX - cacheSoloPointer.x;
  40081. var offsetY = evt.clientY - cacheSoloPointer.y;
  40082. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40083. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40084. }
  40085. cacheSoloPointer.x = evt.clientX;
  40086. cacheSoloPointer.y = evt.clientY;
  40087. }
  40088. else if (pointA && pointB) {
  40089. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40090. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40091. ed.x = evt.clientX;
  40092. ed.y = evt.clientY;
  40093. var direction = _this.pinchInwards ? 1 : -1;
  40094. var distX = pointA.x - pointB.x;
  40095. var distY = pointA.y - pointB.y;
  40096. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40097. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40098. if (previousPinchSquaredDistance === 0) {
  40099. initialDistance = pinchDistance;
  40100. previousPinchSquaredDistance = pinchSquaredDistance;
  40101. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40102. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40103. return;
  40104. }
  40105. if (_this.multiTouchPanAndZoom) {
  40106. if (_this.pinchDeltaPercentage) {
  40107. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40108. }
  40109. else {
  40110. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40111. (_this.pinchPrecision *
  40112. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40113. direction);
  40114. }
  40115. if (_this.panningSensibility !== 0) {
  40116. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40117. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40118. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40119. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40120. previousMultiTouchPanPosition.x = pointersCenterX;
  40121. previousMultiTouchPanPosition.y = pointersCenterY;
  40122. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40123. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40124. }
  40125. }
  40126. else {
  40127. twoFingerActivityCount++;
  40128. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40129. if (_this.pinchDeltaPercentage) {
  40130. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40131. }
  40132. else {
  40133. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40134. (_this.pinchPrecision *
  40135. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40136. direction);
  40137. }
  40138. previousMultiTouchPanPosition.isPaning = false;
  40139. previousMultiTouchPanPosition.isPinching = true;
  40140. }
  40141. else {
  40142. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40143. if (!previousMultiTouchPanPosition.isPaning) {
  40144. previousMultiTouchPanPosition.isPaning = true;
  40145. previousMultiTouchPanPosition.isPinching = false;
  40146. previousMultiTouchPanPosition.x = ed.x;
  40147. previousMultiTouchPanPosition.y = ed.y;
  40148. return;
  40149. }
  40150. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40151. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40152. }
  40153. }
  40154. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40155. previousMultiTouchPanPosition.x = ed.x;
  40156. previousMultiTouchPanPosition.y = ed.y;
  40157. }
  40158. }
  40159. previousPinchSquaredDistance = pinchSquaredDistance;
  40160. }
  40161. }
  40162. };
  40163. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40164. this._onContextMenu = function (evt) {
  40165. evt.preventDefault();
  40166. };
  40167. if (!this.camera._useCtrlForPanning) {
  40168. element.addEventListener("contextmenu", this._onContextMenu, false);
  40169. }
  40170. this._onLostFocus = function () {
  40171. //this._keys = [];
  40172. pointA = pointB = null;
  40173. previousPinchSquaredDistance = 0;
  40174. previousMultiTouchPanPosition.isPaning = false;
  40175. previousMultiTouchPanPosition.isPinching = false;
  40176. twoFingerActivityCount = 0;
  40177. cacheSoloPointer = null;
  40178. initialDistance = 0;
  40179. };
  40180. this._onMouseMove = function (evt) {
  40181. if (!engine.isPointerLock) {
  40182. return;
  40183. }
  40184. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40185. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40186. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40187. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40188. if (!noPreventDefault) {
  40189. evt.preventDefault();
  40190. }
  40191. };
  40192. this._onGestureStart = function (e) {
  40193. if (window.MSGesture === undefined) {
  40194. return;
  40195. }
  40196. if (!_this._MSGestureHandler) {
  40197. _this._MSGestureHandler = new MSGesture();
  40198. _this._MSGestureHandler.target = element;
  40199. }
  40200. _this._MSGestureHandler.addPointer(e.pointerId);
  40201. };
  40202. this._onGesture = function (e) {
  40203. _this.camera.radius *= e.scale;
  40204. if (e.preventDefault) {
  40205. if (!noPreventDefault) {
  40206. e.stopPropagation();
  40207. e.preventDefault();
  40208. }
  40209. }
  40210. };
  40211. element.addEventListener("mousemove", this._onMouseMove, false);
  40212. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40213. element.addEventListener("MSGestureChange", this._onGesture, false);
  40214. BABYLON.Tools.RegisterTopRootEvents([
  40215. { name: "blur", handler: this._onLostFocus }
  40216. ]);
  40217. };
  40218. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40219. if (this._onLostFocus) {
  40220. BABYLON.Tools.UnregisterTopRootEvents([
  40221. { name: "blur", handler: this._onLostFocus }
  40222. ]);
  40223. }
  40224. if (element && this._observer) {
  40225. this.camera.getScene().onPointerObservable.remove(this._observer);
  40226. this._observer = null;
  40227. if (this._onContextMenu) {
  40228. element.removeEventListener("contextmenu", this._onContextMenu);
  40229. }
  40230. if (this._onMouseMove) {
  40231. element.removeEventListener("mousemove", this._onMouseMove);
  40232. }
  40233. if (this._onGestureStart) {
  40234. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40235. }
  40236. if (this._onGesture) {
  40237. element.removeEventListener("MSGestureChange", this._onGesture);
  40238. }
  40239. this._isPanClick = false;
  40240. this.pinchInwards = true;
  40241. this._onMouseMove = null;
  40242. this._onGestureStart = null;
  40243. this._onGesture = null;
  40244. this._MSGestureHandler = null;
  40245. this._onLostFocus = null;
  40246. this._onContextMenu = null;
  40247. }
  40248. };
  40249. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40250. return "ArcRotateCameraPointersInput";
  40251. };
  40252. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40253. return "pointers";
  40254. };
  40255. __decorate([
  40256. BABYLON.serialize()
  40257. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40258. __decorate([
  40259. BABYLON.serialize()
  40260. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40261. __decorate([
  40262. BABYLON.serialize()
  40263. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40264. __decorate([
  40265. BABYLON.serialize()
  40266. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40267. __decorate([
  40268. BABYLON.serialize()
  40269. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40270. __decorate([
  40271. BABYLON.serialize()
  40272. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40273. __decorate([
  40274. BABYLON.serialize()
  40275. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40276. __decorate([
  40277. BABYLON.serialize()
  40278. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40279. return ArcRotateCameraPointersInput;
  40280. }());
  40281. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40282. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40283. })(BABYLON || (BABYLON = {}));
  40284. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40285. var BABYLON;
  40286. (function (BABYLON) {
  40287. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40288. __extends(ArcRotateCameraInputsManager, _super);
  40289. function ArcRotateCameraInputsManager(camera) {
  40290. return _super.call(this, camera) || this;
  40291. }
  40292. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40293. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40294. return this;
  40295. };
  40296. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40297. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40298. return this;
  40299. };
  40300. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40301. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40302. return this;
  40303. };
  40304. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40305. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40306. return this;
  40307. };
  40308. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40309. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40310. return this;
  40311. };
  40312. return ArcRotateCameraInputsManager;
  40313. }(BABYLON.CameraInputsManager));
  40314. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40315. })(BABYLON || (BABYLON = {}));
  40316. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40317. var BABYLON;
  40318. (function (BABYLON) {
  40319. var ArcRotateCamera = /** @class */ (function (_super) {
  40320. __extends(ArcRotateCamera, _super);
  40321. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40322. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40323. _this.inertialAlphaOffset = 0;
  40324. _this.inertialBetaOffset = 0;
  40325. _this.inertialRadiusOffset = 0;
  40326. _this.lowerAlphaLimit = null;
  40327. _this.upperAlphaLimit = null;
  40328. _this.lowerBetaLimit = 0.01;
  40329. _this.upperBetaLimit = Math.PI;
  40330. _this.lowerRadiusLimit = null;
  40331. _this.upperRadiusLimit = null;
  40332. _this.inertialPanningX = 0;
  40333. _this.inertialPanningY = 0;
  40334. _this.pinchToPanMaxDistance = 20;
  40335. _this.panningDistanceLimit = null;
  40336. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40337. _this.panningInertia = 0.9;
  40338. //-- end properties for backward compatibility for inputs
  40339. _this.zoomOnFactor = 1;
  40340. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40341. _this.allowUpsideDown = true;
  40342. _this._viewMatrix = new BABYLON.Matrix();
  40343. // Panning
  40344. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40345. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40346. _this.checkCollisions = false;
  40347. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40348. _this._previousPosition = BABYLON.Vector3.Zero();
  40349. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40350. _this._newPosition = BABYLON.Vector3.Zero();
  40351. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40352. if (collidedMesh === void 0) { collidedMesh = null; }
  40353. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40354. newPosition.multiplyInPlace(_this._collider._radius);
  40355. }
  40356. if (!collidedMesh) {
  40357. _this._previousPosition.copyFrom(_this.position);
  40358. }
  40359. else {
  40360. _this.setPosition(newPosition);
  40361. if (_this.onCollide) {
  40362. _this.onCollide(collidedMesh);
  40363. }
  40364. }
  40365. // Recompute because of constraints
  40366. var cosa = Math.cos(_this.alpha);
  40367. var sina = Math.sin(_this.alpha);
  40368. var cosb = Math.cos(_this.beta);
  40369. var sinb = Math.sin(_this.beta);
  40370. if (sinb === 0) {
  40371. sinb = 0.0001;
  40372. }
  40373. var target = _this._getTargetPosition();
  40374. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40375. _this.position.copyFrom(_this._newPosition);
  40376. var up = _this.upVector;
  40377. if (_this.allowUpsideDown && _this.beta < 0) {
  40378. up = up.clone();
  40379. up = up.negate();
  40380. }
  40381. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40382. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40383. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40384. _this._collisionTriggered = false;
  40385. };
  40386. _this._target = BABYLON.Vector3.Zero();
  40387. if (target) {
  40388. _this.setTarget(target);
  40389. }
  40390. _this.alpha = alpha;
  40391. _this.beta = beta;
  40392. _this.radius = radius;
  40393. _this.getViewMatrix();
  40394. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40395. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40396. return _this;
  40397. }
  40398. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40399. get: function () {
  40400. return this._target;
  40401. },
  40402. set: function (value) {
  40403. this.setTarget(value);
  40404. },
  40405. enumerable: true,
  40406. configurable: true
  40407. });
  40408. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40409. //-- begin properties for backward compatibility for inputs
  40410. get: function () {
  40411. var pointers = this.inputs.attached["pointers"];
  40412. if (pointers)
  40413. return pointers.angularSensibilityX;
  40414. return 0;
  40415. },
  40416. set: function (value) {
  40417. var pointers = this.inputs.attached["pointers"];
  40418. if (pointers) {
  40419. pointers.angularSensibilityX = value;
  40420. }
  40421. },
  40422. enumerable: true,
  40423. configurable: true
  40424. });
  40425. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40426. get: function () {
  40427. var pointers = this.inputs.attached["pointers"];
  40428. if (pointers)
  40429. return pointers.angularSensibilityY;
  40430. return 0;
  40431. },
  40432. set: function (value) {
  40433. var pointers = this.inputs.attached["pointers"];
  40434. if (pointers) {
  40435. pointers.angularSensibilityY = value;
  40436. }
  40437. },
  40438. enumerable: true,
  40439. configurable: true
  40440. });
  40441. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40442. get: function () {
  40443. var pointers = this.inputs.attached["pointers"];
  40444. if (pointers)
  40445. return pointers.pinchPrecision;
  40446. return 0;
  40447. },
  40448. set: function (value) {
  40449. var pointers = this.inputs.attached["pointers"];
  40450. if (pointers) {
  40451. pointers.pinchPrecision = value;
  40452. }
  40453. },
  40454. enumerable: true,
  40455. configurable: true
  40456. });
  40457. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40458. get: function () {
  40459. var pointers = this.inputs.attached["pointers"];
  40460. if (pointers)
  40461. return pointers.pinchDeltaPercentage;
  40462. return 0;
  40463. },
  40464. set: function (value) {
  40465. var pointers = this.inputs.attached["pointers"];
  40466. if (pointers) {
  40467. pointers.pinchDeltaPercentage = value;
  40468. }
  40469. },
  40470. enumerable: true,
  40471. configurable: true
  40472. });
  40473. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40474. get: function () {
  40475. var pointers = this.inputs.attached["pointers"];
  40476. if (pointers)
  40477. return pointers.panningSensibility;
  40478. return 0;
  40479. },
  40480. set: function (value) {
  40481. var pointers = this.inputs.attached["pointers"];
  40482. if (pointers) {
  40483. pointers.panningSensibility = value;
  40484. }
  40485. },
  40486. enumerable: true,
  40487. configurable: true
  40488. });
  40489. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40490. get: function () {
  40491. var keyboard = this.inputs.attached["keyboard"];
  40492. if (keyboard)
  40493. return keyboard.keysUp;
  40494. return [];
  40495. },
  40496. set: function (value) {
  40497. var keyboard = this.inputs.attached["keyboard"];
  40498. if (keyboard)
  40499. keyboard.keysUp = value;
  40500. },
  40501. enumerable: true,
  40502. configurable: true
  40503. });
  40504. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40505. get: function () {
  40506. var keyboard = this.inputs.attached["keyboard"];
  40507. if (keyboard)
  40508. return keyboard.keysDown;
  40509. return [];
  40510. },
  40511. set: function (value) {
  40512. var keyboard = this.inputs.attached["keyboard"];
  40513. if (keyboard)
  40514. keyboard.keysDown = value;
  40515. },
  40516. enumerable: true,
  40517. configurable: true
  40518. });
  40519. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40520. get: function () {
  40521. var keyboard = this.inputs.attached["keyboard"];
  40522. if (keyboard)
  40523. return keyboard.keysLeft;
  40524. return [];
  40525. },
  40526. set: function (value) {
  40527. var keyboard = this.inputs.attached["keyboard"];
  40528. if (keyboard)
  40529. keyboard.keysLeft = value;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40535. get: function () {
  40536. var keyboard = this.inputs.attached["keyboard"];
  40537. if (keyboard)
  40538. return keyboard.keysRight;
  40539. return [];
  40540. },
  40541. set: function (value) {
  40542. var keyboard = this.inputs.attached["keyboard"];
  40543. if (keyboard)
  40544. keyboard.keysRight = value;
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40550. get: function () {
  40551. var mousewheel = this.inputs.attached["mousewheel"];
  40552. if (mousewheel)
  40553. return mousewheel.wheelPrecision;
  40554. return 0;
  40555. },
  40556. set: function (value) {
  40557. var mousewheel = this.inputs.attached["mousewheel"];
  40558. if (mousewheel)
  40559. mousewheel.wheelPrecision = value;
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40565. get: function () {
  40566. var mousewheel = this.inputs.attached["mousewheel"];
  40567. if (mousewheel)
  40568. return mousewheel.wheelDeltaPercentage;
  40569. return 0;
  40570. },
  40571. set: function (value) {
  40572. var mousewheel = this.inputs.attached["mousewheel"];
  40573. if (mousewheel)
  40574. mousewheel.wheelDeltaPercentage = value;
  40575. },
  40576. enumerable: true,
  40577. configurable: true
  40578. });
  40579. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40580. get: function () {
  40581. return this._bouncingBehavior;
  40582. },
  40583. enumerable: true,
  40584. configurable: true
  40585. });
  40586. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40587. get: function () {
  40588. return this._bouncingBehavior != null;
  40589. },
  40590. set: function (value) {
  40591. if (value === this.useBouncingBehavior) {
  40592. return;
  40593. }
  40594. if (value) {
  40595. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40596. this.addBehavior(this._bouncingBehavior);
  40597. }
  40598. else if (this._bouncingBehavior) {
  40599. this.removeBehavior(this._bouncingBehavior);
  40600. this._bouncingBehavior = null;
  40601. }
  40602. },
  40603. enumerable: true,
  40604. configurable: true
  40605. });
  40606. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40607. get: function () {
  40608. return this._framingBehavior;
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40614. get: function () {
  40615. return this._framingBehavior != null;
  40616. },
  40617. set: function (value) {
  40618. if (value === this.useFramingBehavior) {
  40619. return;
  40620. }
  40621. if (value) {
  40622. this._framingBehavior = new BABYLON.FramingBehavior();
  40623. this.addBehavior(this._framingBehavior);
  40624. }
  40625. else if (this._framingBehavior) {
  40626. this.removeBehavior(this._framingBehavior);
  40627. this._framingBehavior = null;
  40628. }
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40634. get: function () {
  40635. return this._autoRotationBehavior;
  40636. },
  40637. enumerable: true,
  40638. configurable: true
  40639. });
  40640. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40641. get: function () {
  40642. return this._autoRotationBehavior != null;
  40643. },
  40644. set: function (value) {
  40645. if (value === this.useAutoRotationBehavior) {
  40646. return;
  40647. }
  40648. if (value) {
  40649. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40650. this.addBehavior(this._autoRotationBehavior);
  40651. }
  40652. else if (this._autoRotationBehavior) {
  40653. this.removeBehavior(this._autoRotationBehavior);
  40654. this._autoRotationBehavior = null;
  40655. }
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. // Cache
  40661. ArcRotateCamera.prototype._initCache = function () {
  40662. _super.prototype._initCache.call(this);
  40663. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40664. this._cache.alpha = undefined;
  40665. this._cache.beta = undefined;
  40666. this._cache.radius = undefined;
  40667. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40668. };
  40669. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40670. if (!ignoreParentClass) {
  40671. _super.prototype._updateCache.call(this);
  40672. }
  40673. this._cache._target.copyFrom(this._getTargetPosition());
  40674. this._cache.alpha = this.alpha;
  40675. this._cache.beta = this.beta;
  40676. this._cache.radius = this.radius;
  40677. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40678. };
  40679. ArcRotateCamera.prototype._getTargetPosition = function () {
  40680. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40681. var pos = this._targetHost.getAbsolutePosition();
  40682. if (this._targetBoundingCenter) {
  40683. pos.addToRef(this._targetBoundingCenter, this._target);
  40684. }
  40685. else {
  40686. this._target.copyFrom(pos);
  40687. }
  40688. }
  40689. var lockedTargetPosition = this._getLockedTargetPosition();
  40690. if (lockedTargetPosition) {
  40691. return lockedTargetPosition;
  40692. }
  40693. return this._target;
  40694. };
  40695. ArcRotateCamera.prototype.storeState = function () {
  40696. this._storedAlpha = this.alpha;
  40697. this._storedBeta = this.beta;
  40698. this._storedRadius = this.radius;
  40699. this._storedTarget = this._getTargetPosition().clone();
  40700. return _super.prototype.storeState.call(this);
  40701. };
  40702. /**
  40703. * Restored camera state. You must call storeState() first
  40704. */
  40705. ArcRotateCamera.prototype._restoreStateValues = function () {
  40706. if (!_super.prototype._restoreStateValues.call(this)) {
  40707. return false;
  40708. }
  40709. this.alpha = this._storedAlpha;
  40710. this.beta = this._storedBeta;
  40711. this.radius = this._storedRadius;
  40712. this.setTarget(this._storedTarget.clone());
  40713. this.inertialAlphaOffset = 0;
  40714. this.inertialBetaOffset = 0;
  40715. this.inertialRadiusOffset = 0;
  40716. this.inertialPanningX = 0;
  40717. this.inertialPanningY = 0;
  40718. return true;
  40719. };
  40720. // Synchronized
  40721. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40722. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40723. return false;
  40724. return this._cache._target.equals(this._getTargetPosition())
  40725. && this._cache.alpha === this.alpha
  40726. && this._cache.beta === this.beta
  40727. && this._cache.radius === this.radius
  40728. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40729. };
  40730. // Methods
  40731. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40732. var _this = this;
  40733. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40734. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40735. this._useCtrlForPanning = useCtrlForPanning;
  40736. this._panningMouseButton = panningMouseButton;
  40737. this.inputs.attachElement(element, noPreventDefault);
  40738. this._reset = function () {
  40739. _this.inertialAlphaOffset = 0;
  40740. _this.inertialBetaOffset = 0;
  40741. _this.inertialRadiusOffset = 0;
  40742. _this.inertialPanningX = 0;
  40743. _this.inertialPanningY = 0;
  40744. };
  40745. };
  40746. ArcRotateCamera.prototype.detachControl = function (element) {
  40747. this.inputs.detachElement(element);
  40748. if (this._reset) {
  40749. this._reset();
  40750. }
  40751. };
  40752. ArcRotateCamera.prototype._checkInputs = function () {
  40753. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40754. if (this._collisionTriggered) {
  40755. return;
  40756. }
  40757. this.inputs.checkInputs();
  40758. // Inertia
  40759. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40760. if (this.getScene().useRightHandedSystem) {
  40761. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40762. }
  40763. else {
  40764. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40765. }
  40766. this.beta += this.inertialBetaOffset;
  40767. this.radius -= this.inertialRadiusOffset;
  40768. this.inertialAlphaOffset *= this.inertia;
  40769. this.inertialBetaOffset *= this.inertia;
  40770. this.inertialRadiusOffset *= this.inertia;
  40771. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40772. this.inertialAlphaOffset = 0;
  40773. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40774. this.inertialBetaOffset = 0;
  40775. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40776. this.inertialRadiusOffset = 0;
  40777. }
  40778. // Panning inertia
  40779. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40780. if (!this._localDirection) {
  40781. this._localDirection = BABYLON.Vector3.Zero();
  40782. this._transformedDirection = BABYLON.Vector3.Zero();
  40783. }
  40784. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40785. this._localDirection.multiplyInPlace(this.panningAxis);
  40786. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40787. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40788. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40789. if (!this.panningAxis.y) {
  40790. this._transformedDirection.y = 0;
  40791. }
  40792. if (!this._targetHost) {
  40793. if (this.panningDistanceLimit) {
  40794. this._transformedDirection.addInPlace(this._target);
  40795. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40796. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40797. this._target.copyFrom(this._transformedDirection);
  40798. }
  40799. }
  40800. else {
  40801. this._target.addInPlace(this._transformedDirection);
  40802. }
  40803. }
  40804. this.inertialPanningX *= this.panningInertia;
  40805. this.inertialPanningY *= this.panningInertia;
  40806. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40807. this.inertialPanningX = 0;
  40808. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40809. this.inertialPanningY = 0;
  40810. }
  40811. // Limits
  40812. this._checkLimits();
  40813. _super.prototype._checkInputs.call(this);
  40814. };
  40815. ArcRotateCamera.prototype._checkLimits = function () {
  40816. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40817. if (this.allowUpsideDown && this.beta > Math.PI) {
  40818. this.beta = this.beta - (2 * Math.PI);
  40819. }
  40820. }
  40821. else {
  40822. if (this.beta < this.lowerBetaLimit) {
  40823. this.beta = this.lowerBetaLimit;
  40824. }
  40825. }
  40826. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40827. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40828. this.beta = this.beta + (2 * Math.PI);
  40829. }
  40830. }
  40831. else {
  40832. if (this.beta > this.upperBetaLimit) {
  40833. this.beta = this.upperBetaLimit;
  40834. }
  40835. }
  40836. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40837. this.alpha = this.lowerAlphaLimit;
  40838. }
  40839. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40840. this.alpha = this.upperAlphaLimit;
  40841. }
  40842. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40843. this.radius = this.lowerRadiusLimit;
  40844. }
  40845. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40846. this.radius = this.upperRadiusLimit;
  40847. }
  40848. };
  40849. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40850. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40851. this.radius = radiusv3.length();
  40852. if (this.radius === 0) {
  40853. this.radius = 0.0001; // Just to avoid division by zero
  40854. }
  40855. // Alpha
  40856. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40857. if (radiusv3.z < 0) {
  40858. this.alpha = 2 * Math.PI - this.alpha;
  40859. }
  40860. // Beta
  40861. this.beta = Math.acos(radiusv3.y / this.radius);
  40862. this._checkLimits();
  40863. };
  40864. ArcRotateCamera.prototype.setPosition = function (position) {
  40865. if (this.position.equals(position)) {
  40866. return;
  40867. }
  40868. this.position.copyFrom(position);
  40869. this.rebuildAnglesAndRadius();
  40870. };
  40871. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40872. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40873. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40874. if (target.getBoundingInfo) {
  40875. if (toBoundingCenter) {
  40876. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40877. }
  40878. else {
  40879. this._targetBoundingCenter = null;
  40880. }
  40881. this._targetHost = target;
  40882. this._target = this._getTargetPosition();
  40883. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40884. }
  40885. else {
  40886. var newTarget = target;
  40887. var currentTarget = this._getTargetPosition();
  40888. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40889. return;
  40890. }
  40891. this._targetHost = null;
  40892. this._target = newTarget;
  40893. this._targetBoundingCenter = null;
  40894. this.onMeshTargetChangedObservable.notifyObservers(null);
  40895. }
  40896. this.rebuildAnglesAndRadius();
  40897. };
  40898. ArcRotateCamera.prototype._getViewMatrix = function () {
  40899. // Compute
  40900. var cosa = Math.cos(this.alpha);
  40901. var sina = Math.sin(this.alpha);
  40902. var cosb = Math.cos(this.beta);
  40903. var sinb = Math.sin(this.beta);
  40904. if (sinb === 0) {
  40905. sinb = 0.0001;
  40906. }
  40907. var target = this._getTargetPosition();
  40908. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40909. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40910. if (!this._collider) {
  40911. this._collider = new BABYLON.Collider();
  40912. }
  40913. this._collider._radius = this.collisionRadius;
  40914. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40915. this._collisionTriggered = true;
  40916. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40917. }
  40918. else {
  40919. this.position.copyFrom(this._newPosition);
  40920. var up = this.upVector;
  40921. if (this.allowUpsideDown && sinb < 0) {
  40922. up = up.clone();
  40923. up = up.negate();
  40924. }
  40925. if (this.getScene().useRightHandedSystem) {
  40926. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40927. }
  40928. else {
  40929. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40930. }
  40931. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40932. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40933. }
  40934. this._currentTarget = target;
  40935. return this._viewMatrix;
  40936. };
  40937. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40938. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40939. meshes = meshes || this.getScene().meshes;
  40940. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40941. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40942. this.radius = distance * this.zoomOnFactor;
  40943. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40944. };
  40945. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40946. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40947. var meshesOrMinMaxVector;
  40948. var distance;
  40949. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40950. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40951. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40952. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40953. }
  40954. else {
  40955. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40956. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40957. distance = minMaxVectorAndDistance.distance;
  40958. }
  40959. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40960. if (!doNotUpdateMaxZ) {
  40961. this.maxZ = distance * 2;
  40962. }
  40963. };
  40964. /**
  40965. * @override
  40966. * Override Camera.createRigCamera
  40967. */
  40968. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40969. var alphaShift = 0;
  40970. switch (this.cameraRigMode) {
  40971. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40972. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40974. case BABYLON.Camera.RIG_MODE_VR:
  40975. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40976. break;
  40977. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40978. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40979. break;
  40980. }
  40981. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40982. rigCam._cameraRigParams = {};
  40983. return rigCam;
  40984. };
  40985. /**
  40986. * @override
  40987. * Override Camera._updateRigCameras
  40988. */
  40989. ArcRotateCamera.prototype._updateRigCameras = function () {
  40990. var camLeft = this._rigCameras[0];
  40991. var camRight = this._rigCameras[1];
  40992. camLeft.beta = camRight.beta = this.beta;
  40993. camLeft.radius = camRight.radius = this.radius;
  40994. switch (this.cameraRigMode) {
  40995. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40996. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40998. case BABYLON.Camera.RIG_MODE_VR:
  40999. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41000. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41001. break;
  41002. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41003. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41004. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41005. break;
  41006. }
  41007. _super.prototype._updateRigCameras.call(this);
  41008. };
  41009. ArcRotateCamera.prototype.dispose = function () {
  41010. this.inputs.clear();
  41011. _super.prototype.dispose.call(this);
  41012. };
  41013. ArcRotateCamera.prototype.getClassName = function () {
  41014. return "ArcRotateCamera";
  41015. };
  41016. __decorate([
  41017. BABYLON.serialize()
  41018. ], ArcRotateCamera.prototype, "alpha", void 0);
  41019. __decorate([
  41020. BABYLON.serialize()
  41021. ], ArcRotateCamera.prototype, "beta", void 0);
  41022. __decorate([
  41023. BABYLON.serialize()
  41024. ], ArcRotateCamera.prototype, "radius", void 0);
  41025. __decorate([
  41026. BABYLON.serializeAsVector3("target")
  41027. ], ArcRotateCamera.prototype, "_target", void 0);
  41028. __decorate([
  41029. BABYLON.serialize()
  41030. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41031. __decorate([
  41032. BABYLON.serialize()
  41033. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41034. __decorate([
  41035. BABYLON.serialize()
  41036. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41037. __decorate([
  41038. BABYLON.serialize()
  41039. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41040. __decorate([
  41041. BABYLON.serialize()
  41042. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41043. __decorate([
  41044. BABYLON.serialize()
  41045. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41046. __decorate([
  41047. BABYLON.serialize()
  41048. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41049. __decorate([
  41050. BABYLON.serialize()
  41051. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41052. __decorate([
  41053. BABYLON.serialize()
  41054. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41055. __decorate([
  41056. BABYLON.serialize()
  41057. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41058. __decorate([
  41059. BABYLON.serialize()
  41060. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41061. __decorate([
  41062. BABYLON.serialize()
  41063. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41064. __decorate([
  41065. BABYLON.serialize()
  41066. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41067. __decorate([
  41068. BABYLON.serializeAsVector3()
  41069. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41070. __decorate([
  41071. BABYLON.serialize()
  41072. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41073. __decorate([
  41074. BABYLON.serialize()
  41075. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41076. __decorate([
  41077. BABYLON.serialize()
  41078. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41079. return ArcRotateCamera;
  41080. }(BABYLON.TargetCamera));
  41081. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41082. })(BABYLON || (BABYLON = {}));
  41083. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41084. var BABYLON;
  41085. (function (BABYLON) {
  41086. var HemisphericLight = /** @class */ (function (_super) {
  41087. __extends(HemisphericLight, _super);
  41088. /**
  41089. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41090. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41091. * The HemisphericLight can't cast shadows.
  41092. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41093. */
  41094. function HemisphericLight(name, direction, scene) {
  41095. var _this = _super.call(this, name, scene) || this;
  41096. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41097. _this.direction = direction || BABYLON.Vector3.Up();
  41098. return _this;
  41099. }
  41100. HemisphericLight.prototype._buildUniformLayout = function () {
  41101. this._uniformBuffer.addUniform("vLightData", 4);
  41102. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41103. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41104. this._uniformBuffer.addUniform("vLightGround", 3);
  41105. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41106. this._uniformBuffer.addUniform("depthValues", 2);
  41107. this._uniformBuffer.create();
  41108. };
  41109. /**
  41110. * Returns the string "HemisphericLight".
  41111. */
  41112. HemisphericLight.prototype.getClassName = function () {
  41113. return "HemisphericLight";
  41114. };
  41115. /**
  41116. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41117. * Returns the updated direction.
  41118. */
  41119. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41120. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41121. return this.direction;
  41122. };
  41123. HemisphericLight.prototype.getShadowGenerator = function () {
  41124. return null;
  41125. };
  41126. /**
  41127. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41128. * Returns the HemisphericLight.
  41129. */
  41130. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41131. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41132. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41133. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41134. return this;
  41135. };
  41136. HemisphericLight.prototype._getWorldMatrix = function () {
  41137. if (!this._worldMatrix) {
  41138. this._worldMatrix = BABYLON.Matrix.Identity();
  41139. }
  41140. return this._worldMatrix;
  41141. };
  41142. /**
  41143. * Returns the integer 3.
  41144. */
  41145. HemisphericLight.prototype.getTypeID = function () {
  41146. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41147. };
  41148. __decorate([
  41149. BABYLON.serializeAsColor3()
  41150. ], HemisphericLight.prototype, "groundColor", void 0);
  41151. __decorate([
  41152. BABYLON.serializeAsVector3()
  41153. ], HemisphericLight.prototype, "direction", void 0);
  41154. return HemisphericLight;
  41155. }(BABYLON.Light));
  41156. BABYLON.HemisphericLight = HemisphericLight;
  41157. })(BABYLON || (BABYLON = {}));
  41158. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41159. var BABYLON;
  41160. (function (BABYLON) {
  41161. var ShadowLight = /** @class */ (function (_super) {
  41162. __extends(ShadowLight, _super);
  41163. function ShadowLight() {
  41164. var _this = _super !== null && _super.apply(this, arguments) || this;
  41165. _this._needProjectionMatrixCompute = true;
  41166. return _this;
  41167. }
  41168. Object.defineProperty(ShadowLight.prototype, "direction", {
  41169. get: function () {
  41170. return this._direction;
  41171. },
  41172. set: function (value) {
  41173. this._direction = value;
  41174. },
  41175. enumerable: true,
  41176. configurable: true
  41177. });
  41178. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41179. get: function () {
  41180. return this._shadowMinZ;
  41181. },
  41182. set: function (value) {
  41183. this._shadowMinZ = value;
  41184. this.forceProjectionMatrixCompute();
  41185. },
  41186. enumerable: true,
  41187. configurable: true
  41188. });
  41189. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41190. get: function () {
  41191. return this._shadowMaxZ;
  41192. },
  41193. set: function (value) {
  41194. this._shadowMaxZ = value;
  41195. this.forceProjectionMatrixCompute();
  41196. },
  41197. enumerable: true,
  41198. configurable: true
  41199. });
  41200. /**
  41201. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41202. */
  41203. ShadowLight.prototype.computeTransformedInformation = function () {
  41204. if (this.parent && this.parent.getWorldMatrix) {
  41205. if (!this.transformedPosition) {
  41206. this.transformedPosition = BABYLON.Vector3.Zero();
  41207. }
  41208. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41209. // In case the direction is present.
  41210. if (this.direction) {
  41211. if (!this.transformedDirection) {
  41212. this.transformedDirection = BABYLON.Vector3.Zero();
  41213. }
  41214. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41215. }
  41216. return true;
  41217. }
  41218. return false;
  41219. };
  41220. /**
  41221. * Return the depth scale used for the shadow map.
  41222. */
  41223. ShadowLight.prototype.getDepthScale = function () {
  41224. return 50.0;
  41225. };
  41226. /**
  41227. * Returns the light direction (Vector3) for any passed face index.
  41228. */
  41229. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41230. return this.transformedDirection ? this.transformedDirection : this.direction;
  41231. };
  41232. /**
  41233. * Returns the ShadowLight absolute position in the World.
  41234. */
  41235. ShadowLight.prototype.getAbsolutePosition = function () {
  41236. return this.transformedPosition ? this.transformedPosition : this.position;
  41237. };
  41238. /**
  41239. * Sets the ShadowLight direction toward the passed target (Vector3).
  41240. * Returns the updated ShadowLight direction (Vector3).
  41241. */
  41242. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41243. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41244. return this.direction;
  41245. };
  41246. /**
  41247. * Returns the light rotation (Vector3).
  41248. */
  41249. ShadowLight.prototype.getRotation = function () {
  41250. this.direction.normalize();
  41251. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41252. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41253. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41254. };
  41255. /**
  41256. * Boolean : false by default.
  41257. */
  41258. ShadowLight.prototype.needCube = function () {
  41259. return false;
  41260. };
  41261. /**
  41262. * Specifies wether or not the projection matrix should be recomputed this frame.
  41263. */
  41264. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41265. return this._needProjectionMatrixCompute;
  41266. };
  41267. /**
  41268. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41269. */
  41270. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41271. this._needProjectionMatrixCompute = true;
  41272. };
  41273. /**
  41274. * Get the world matrix of the sahdow lights.
  41275. */
  41276. ShadowLight.prototype._getWorldMatrix = function () {
  41277. if (!this._worldMatrix) {
  41278. this._worldMatrix = BABYLON.Matrix.Identity();
  41279. }
  41280. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41281. return this._worldMatrix;
  41282. };
  41283. /**
  41284. * Gets the minZ used for shadow according to both the scene and the light.
  41285. * @param activeCamera
  41286. */
  41287. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41288. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41289. };
  41290. /**
  41291. * Gets the maxZ used for shadow according to both the scene and the light.
  41292. * @param activeCamera
  41293. */
  41294. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41295. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41296. };
  41297. /**
  41298. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41299. * Returns the light.
  41300. */
  41301. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41302. if (this.customProjectionMatrixBuilder) {
  41303. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41304. }
  41305. else {
  41306. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41307. }
  41308. return this;
  41309. };
  41310. __decorate([
  41311. BABYLON.serializeAsVector3()
  41312. ], ShadowLight.prototype, "position", void 0);
  41313. __decorate([
  41314. BABYLON.serializeAsVector3()
  41315. ], ShadowLight.prototype, "direction", null);
  41316. __decorate([
  41317. BABYLON.serialize()
  41318. ], ShadowLight.prototype, "shadowMinZ", null);
  41319. __decorate([
  41320. BABYLON.serialize()
  41321. ], ShadowLight.prototype, "shadowMaxZ", null);
  41322. return ShadowLight;
  41323. }(BABYLON.Light));
  41324. BABYLON.ShadowLight = ShadowLight;
  41325. })(BABYLON || (BABYLON = {}));
  41326. //# sourceMappingURL=babylon.shadowLight.js.map
  41327. var BABYLON;
  41328. (function (BABYLON) {
  41329. var PointLight = /** @class */ (function (_super) {
  41330. __extends(PointLight, _super);
  41331. /**
  41332. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41333. * A PointLight emits the light in every direction.
  41334. * It can cast shadows.
  41335. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41336. * ```javascript
  41337. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41338. * ```
  41339. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41340. */
  41341. function PointLight(name, position, scene) {
  41342. var _this = _super.call(this, name, scene) || this;
  41343. _this._shadowAngle = Math.PI / 2;
  41344. _this.position = position;
  41345. return _this;
  41346. }
  41347. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41348. /**
  41349. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41350. * This specifies what angle the shadow will use to be created.
  41351. *
  41352. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41353. */
  41354. get: function () {
  41355. return this._shadowAngle;
  41356. },
  41357. /**
  41358. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41359. * This specifies what angle the shadow will use to be created.
  41360. *
  41361. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41362. */
  41363. set: function (value) {
  41364. this._shadowAngle = value;
  41365. this.forceProjectionMatrixCompute();
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(PointLight.prototype, "direction", {
  41371. get: function () {
  41372. return this._direction;
  41373. },
  41374. /**
  41375. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41376. */
  41377. set: function (value) {
  41378. var previousNeedCube = this.needCube();
  41379. this._direction = value;
  41380. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41381. this._shadowGenerator.recreateShadowMap();
  41382. }
  41383. },
  41384. enumerable: true,
  41385. configurable: true
  41386. });
  41387. /**
  41388. * Returns the string "PointLight"
  41389. */
  41390. PointLight.prototype.getClassName = function () {
  41391. return "PointLight";
  41392. };
  41393. /**
  41394. * Returns the integer 0.
  41395. */
  41396. PointLight.prototype.getTypeID = function () {
  41397. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41398. };
  41399. /**
  41400. * Specifies wether or not the shadowmap should be a cube texture.
  41401. */
  41402. PointLight.prototype.needCube = function () {
  41403. return !this.direction;
  41404. };
  41405. /**
  41406. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41407. */
  41408. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41409. if (this.direction) {
  41410. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41411. }
  41412. else {
  41413. switch (faceIndex) {
  41414. case 0:
  41415. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41416. case 1:
  41417. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41418. case 2:
  41419. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41420. case 3:
  41421. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41422. case 4:
  41423. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41424. case 5:
  41425. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41426. }
  41427. }
  41428. return BABYLON.Vector3.Zero();
  41429. };
  41430. /**
  41431. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41432. * - fov = PI / 2
  41433. * - aspect ratio : 1.0
  41434. * - z-near and far equal to the active camera minZ and maxZ.
  41435. * Returns the PointLight.
  41436. */
  41437. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41438. var activeCamera = this.getScene().activeCamera;
  41439. if (!activeCamera) {
  41440. return;
  41441. }
  41442. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41443. };
  41444. PointLight.prototype._buildUniformLayout = function () {
  41445. this._uniformBuffer.addUniform("vLightData", 4);
  41446. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41447. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41448. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41449. this._uniformBuffer.addUniform("depthValues", 2);
  41450. this._uniformBuffer.create();
  41451. };
  41452. /**
  41453. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41454. * Returns the PointLight.
  41455. */
  41456. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41457. if (this.computeTransformedInformation()) {
  41458. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41459. return this;
  41460. }
  41461. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41462. return this;
  41463. };
  41464. __decorate([
  41465. BABYLON.serialize()
  41466. ], PointLight.prototype, "shadowAngle", null);
  41467. return PointLight;
  41468. }(BABYLON.ShadowLight));
  41469. BABYLON.PointLight = PointLight;
  41470. })(BABYLON || (BABYLON = {}));
  41471. //# sourceMappingURL=babylon.pointLight.js.map
  41472. var BABYLON;
  41473. (function (BABYLON) {
  41474. var DirectionalLight = /** @class */ (function (_super) {
  41475. __extends(DirectionalLight, _super);
  41476. /**
  41477. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41478. * The directional light is emitted from everywhere in the given direction.
  41479. * It can cast shawdows.
  41480. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41481. */
  41482. function DirectionalLight(name, direction, scene) {
  41483. var _this = _super.call(this, name, scene) || this;
  41484. _this._shadowFrustumSize = 0;
  41485. _this._shadowOrthoScale = 0.5;
  41486. _this.autoUpdateExtends = true;
  41487. // Cache
  41488. _this._orthoLeft = Number.MAX_VALUE;
  41489. _this._orthoRight = Number.MIN_VALUE;
  41490. _this._orthoTop = Number.MIN_VALUE;
  41491. _this._orthoBottom = Number.MAX_VALUE;
  41492. _this.position = direction.scale(-1.0);
  41493. _this.direction = direction;
  41494. return _this;
  41495. }
  41496. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41497. /**
  41498. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41499. */
  41500. get: function () {
  41501. return this._shadowFrustumSize;
  41502. },
  41503. /**
  41504. * Specifies a fix frustum size for the shadow generation.
  41505. */
  41506. set: function (value) {
  41507. this._shadowFrustumSize = value;
  41508. this.forceProjectionMatrixCompute();
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41514. get: function () {
  41515. return this._shadowOrthoScale;
  41516. },
  41517. set: function (value) {
  41518. this._shadowOrthoScale = value;
  41519. this.forceProjectionMatrixCompute();
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. /**
  41525. * Returns the string "DirectionalLight".
  41526. */
  41527. DirectionalLight.prototype.getClassName = function () {
  41528. return "DirectionalLight";
  41529. };
  41530. /**
  41531. * Returns the integer 1.
  41532. */
  41533. DirectionalLight.prototype.getTypeID = function () {
  41534. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41535. };
  41536. /**
  41537. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41538. * Returns the DirectionalLight Shadow projection matrix.
  41539. */
  41540. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41541. if (this.shadowFrustumSize > 0) {
  41542. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41543. }
  41544. else {
  41545. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41546. }
  41547. };
  41548. /**
  41549. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41550. * Returns the DirectionalLight Shadow projection matrix.
  41551. */
  41552. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41553. var activeCamera = this.getScene().activeCamera;
  41554. if (!activeCamera) {
  41555. return;
  41556. }
  41557. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41558. };
  41559. /**
  41560. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41561. * Returns the DirectionalLight Shadow projection matrix.
  41562. */
  41563. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41564. var activeCamera = this.getScene().activeCamera;
  41565. if (!activeCamera) {
  41566. return;
  41567. }
  41568. // Check extends
  41569. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41570. var tempVector3 = BABYLON.Vector3.Zero();
  41571. this._orthoLeft = Number.MAX_VALUE;
  41572. this._orthoRight = Number.MIN_VALUE;
  41573. this._orthoTop = Number.MIN_VALUE;
  41574. this._orthoBottom = Number.MAX_VALUE;
  41575. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41576. var mesh = renderList[meshIndex];
  41577. if (!mesh) {
  41578. continue;
  41579. }
  41580. var boundingInfo = mesh.getBoundingInfo();
  41581. var boundingBox = boundingInfo.boundingBox;
  41582. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41583. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41584. if (tempVector3.x < this._orthoLeft)
  41585. this._orthoLeft = tempVector3.x;
  41586. if (tempVector3.y < this._orthoBottom)
  41587. this._orthoBottom = tempVector3.y;
  41588. if (tempVector3.x > this._orthoRight)
  41589. this._orthoRight = tempVector3.x;
  41590. if (tempVector3.y > this._orthoTop)
  41591. this._orthoTop = tempVector3.y;
  41592. }
  41593. }
  41594. }
  41595. var xOffset = this._orthoRight - this._orthoLeft;
  41596. var yOffset = this._orthoTop - this._orthoBottom;
  41597. 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);
  41598. };
  41599. DirectionalLight.prototype._buildUniformLayout = function () {
  41600. this._uniformBuffer.addUniform("vLightData", 4);
  41601. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41602. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41603. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41604. this._uniformBuffer.addUniform("depthValues", 2);
  41605. this._uniformBuffer.create();
  41606. };
  41607. /**
  41608. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41609. * Returns the DirectionalLight.
  41610. */
  41611. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41612. if (this.computeTransformedInformation()) {
  41613. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41614. return this;
  41615. }
  41616. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41617. return this;
  41618. };
  41619. /**
  41620. * Gets the minZ used for shadow according to both the scene and the light.
  41621. *
  41622. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41623. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41624. * @param activeCamera
  41625. */
  41626. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41627. return 1;
  41628. };
  41629. /**
  41630. * Gets the maxZ used for shadow according to both the scene and the light.
  41631. *
  41632. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41633. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41634. * @param activeCamera
  41635. */
  41636. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41637. return 1;
  41638. };
  41639. __decorate([
  41640. BABYLON.serialize()
  41641. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41642. __decorate([
  41643. BABYLON.serialize()
  41644. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41645. __decorate([
  41646. BABYLON.serialize()
  41647. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41648. return DirectionalLight;
  41649. }(BABYLON.ShadowLight));
  41650. BABYLON.DirectionalLight = DirectionalLight;
  41651. })(BABYLON || (BABYLON = {}));
  41652. //# sourceMappingURL=babylon.directionalLight.js.map
  41653. var BABYLON;
  41654. (function (BABYLON) {
  41655. var SpotLight = /** @class */ (function (_super) {
  41656. __extends(SpotLight, _super);
  41657. /**
  41658. * Creates a SpotLight object in the scene with the passed parameters :
  41659. * - `position` (Vector3) is the initial SpotLight position,
  41660. * - `direction` (Vector3) is the initial SpotLight direction,
  41661. * - `angle` (float, in radians) is the spot light cone angle,
  41662. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41663. * A spot light is a simply light oriented cone.
  41664. * It can cast shadows.
  41665. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41666. */
  41667. function SpotLight(name, position, direction, angle, exponent, scene) {
  41668. var _this = _super.call(this, name, scene) || this;
  41669. _this.position = position;
  41670. _this.direction = direction;
  41671. _this.angle = angle;
  41672. _this.exponent = exponent;
  41673. return _this;
  41674. }
  41675. Object.defineProperty(SpotLight.prototype, "angle", {
  41676. get: function () {
  41677. return this._angle;
  41678. },
  41679. set: function (value) {
  41680. this._angle = value;
  41681. this.forceProjectionMatrixCompute();
  41682. },
  41683. enumerable: true,
  41684. configurable: true
  41685. });
  41686. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41687. get: function () {
  41688. return this._shadowAngleScale;
  41689. },
  41690. /**
  41691. * Allows scaling the angle of the light for shadow generation only.
  41692. */
  41693. set: function (value) {
  41694. this._shadowAngleScale = value;
  41695. this.forceProjectionMatrixCompute();
  41696. },
  41697. enumerable: true,
  41698. configurable: true
  41699. });
  41700. /**
  41701. * Returns the string "SpotLight".
  41702. */
  41703. SpotLight.prototype.getClassName = function () {
  41704. return "SpotLight";
  41705. };
  41706. /**
  41707. * Returns the integer 2.
  41708. */
  41709. SpotLight.prototype.getTypeID = function () {
  41710. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41711. };
  41712. /**
  41713. * 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.
  41714. * Returns the SpotLight.
  41715. */
  41716. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41717. var activeCamera = this.getScene().activeCamera;
  41718. if (!activeCamera) {
  41719. return;
  41720. }
  41721. this._shadowAngleScale = this._shadowAngleScale || 1;
  41722. var angle = this._shadowAngleScale * this._angle;
  41723. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41724. };
  41725. SpotLight.prototype._buildUniformLayout = function () {
  41726. this._uniformBuffer.addUniform("vLightData", 4);
  41727. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41728. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41729. this._uniformBuffer.addUniform("vLightDirection", 3);
  41730. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41731. this._uniformBuffer.addUniform("depthValues", 2);
  41732. this._uniformBuffer.create();
  41733. };
  41734. /**
  41735. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41736. * Return the SpotLight.
  41737. */
  41738. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41739. var normalizeDirection;
  41740. if (this.computeTransformedInformation()) {
  41741. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41742. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41743. }
  41744. else {
  41745. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41746. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41747. }
  41748. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41749. return this;
  41750. };
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], SpotLight.prototype, "angle", null);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. /**
  41757. * Allows scaling the angle of the light for shadow generation only.
  41758. */
  41759. ], SpotLight.prototype, "shadowAngleScale", null);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], SpotLight.prototype, "exponent", void 0);
  41763. return SpotLight;
  41764. }(BABYLON.ShadowLight));
  41765. BABYLON.SpotLight = SpotLight;
  41766. })(BABYLON || (BABYLON = {}));
  41767. //# sourceMappingURL=babylon.spotLight.js.map
  41768. var BABYLON;
  41769. (function (BABYLON) {
  41770. var AnimationRange = /** @class */ (function () {
  41771. function AnimationRange(name, from, to) {
  41772. this.name = name;
  41773. this.from = from;
  41774. this.to = to;
  41775. }
  41776. AnimationRange.prototype.clone = function () {
  41777. return new AnimationRange(this.name, this.from, this.to);
  41778. };
  41779. return AnimationRange;
  41780. }());
  41781. BABYLON.AnimationRange = AnimationRange;
  41782. /**
  41783. * Composed of a frame, and an action function
  41784. */
  41785. var AnimationEvent = /** @class */ (function () {
  41786. function AnimationEvent(frame, action, onlyOnce) {
  41787. this.frame = frame;
  41788. this.action = action;
  41789. this.onlyOnce = onlyOnce;
  41790. this.isDone = false;
  41791. }
  41792. return AnimationEvent;
  41793. }());
  41794. BABYLON.AnimationEvent = AnimationEvent;
  41795. var PathCursor = /** @class */ (function () {
  41796. function PathCursor(path) {
  41797. this.path = path;
  41798. this._onchange = new Array();
  41799. this.value = 0;
  41800. this.animations = new Array();
  41801. }
  41802. PathCursor.prototype.getPoint = function () {
  41803. var point = this.path.getPointAtLengthPosition(this.value);
  41804. return new BABYLON.Vector3(point.x, 0, point.y);
  41805. };
  41806. PathCursor.prototype.moveAhead = function (step) {
  41807. if (step === void 0) { step = 0.002; }
  41808. this.move(step);
  41809. return this;
  41810. };
  41811. PathCursor.prototype.moveBack = function (step) {
  41812. if (step === void 0) { step = 0.002; }
  41813. this.move(-step);
  41814. return this;
  41815. };
  41816. PathCursor.prototype.move = function (step) {
  41817. if (Math.abs(step) > 1) {
  41818. throw "step size should be less than 1.";
  41819. }
  41820. this.value += step;
  41821. this.ensureLimits();
  41822. this.raiseOnChange();
  41823. return this;
  41824. };
  41825. PathCursor.prototype.ensureLimits = function () {
  41826. while (this.value > 1) {
  41827. this.value -= 1;
  41828. }
  41829. while (this.value < 0) {
  41830. this.value += 1;
  41831. }
  41832. return this;
  41833. };
  41834. // used by animation engine
  41835. PathCursor.prototype.raiseOnChange = function () {
  41836. var _this = this;
  41837. this._onchange.forEach(function (f) { return f(_this); });
  41838. return this;
  41839. };
  41840. PathCursor.prototype.onchange = function (f) {
  41841. this._onchange.push(f);
  41842. return this;
  41843. };
  41844. return PathCursor;
  41845. }());
  41846. BABYLON.PathCursor = PathCursor;
  41847. var AnimationKeyInterpolation;
  41848. (function (AnimationKeyInterpolation) {
  41849. /**
  41850. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41851. */
  41852. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41853. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41854. var Animation = /** @class */ (function () {
  41855. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41856. this.name = name;
  41857. this.targetProperty = targetProperty;
  41858. this.framePerSecond = framePerSecond;
  41859. this.dataType = dataType;
  41860. this.loopMode = loopMode;
  41861. this.enableBlending = enableBlending;
  41862. this._runtimeAnimations = new Array();
  41863. // The set of event that will be linked to this animation
  41864. this._events = new Array();
  41865. this.blendingSpeed = 0.01;
  41866. this._ranges = {};
  41867. this.targetPropertyPath = targetProperty.split(".");
  41868. this.dataType = dataType;
  41869. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41870. }
  41871. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41872. var dataType = undefined;
  41873. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41874. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41875. }
  41876. else if (from instanceof BABYLON.Quaternion) {
  41877. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41878. }
  41879. else if (from instanceof BABYLON.Vector3) {
  41880. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41881. }
  41882. else if (from instanceof BABYLON.Vector2) {
  41883. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41884. }
  41885. else if (from instanceof BABYLON.Color3) {
  41886. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41887. }
  41888. else if (from instanceof BABYLON.Size) {
  41889. dataType = Animation.ANIMATIONTYPE_SIZE;
  41890. }
  41891. if (dataType == undefined) {
  41892. return null;
  41893. }
  41894. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41895. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41896. animation.setKeys(keys);
  41897. if (easingFunction !== undefined) {
  41898. animation.setEasingFunction(easingFunction);
  41899. }
  41900. return animation;
  41901. };
  41902. /**
  41903. * Sets up an animation.
  41904. * @param property the property to animate
  41905. * @param animationType the animation type to apply
  41906. * @param easingFunction the easing function used in the animation
  41907. * @returns The created animation
  41908. */
  41909. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41910. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41911. animation.setEasingFunction(easingFunction);
  41912. return animation;
  41913. };
  41914. /**
  41915. * Create and start an animation on a node
  41916. * @param {string} name defines the name of the global animation that will be run on all nodes
  41917. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41918. * @param {string} targetProperty defines property to animate
  41919. * @param {number} framePerSecond defines the number of frame per second yo use
  41920. * @param {number} totalFrame defines the number of frames in total
  41921. * @param {any} from defines the initial value
  41922. * @param {any} to defines the final value
  41923. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41924. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41925. * @param onAnimationEnd defines the callback to call when animation end
  41926. * @returns the animatable created for this animation
  41927. */
  41928. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41929. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41930. if (!animation) {
  41931. return null;
  41932. }
  41933. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41934. };
  41935. /**
  41936. * Create and start an animation on a node and its descendants
  41937. * @param {string} name defines the name of the global animation that will be run on all nodes
  41938. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41939. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  41940. * @param {string} targetProperty defines property to animate
  41941. * @param {number} framePerSecond defines the number of frame per second yo use
  41942. * @param {number} totalFrame defines the number of frames in total
  41943. * @param {any} from defines the initial value
  41944. * @param {any} to defines the final value
  41945. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41946. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41947. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41948. * @returns the list of animatables created for all nodes
  41949. * @example https://www.babylonjs-playground.com/#MH0VLI
  41950. */
  41951. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41952. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41953. if (!animation) {
  41954. return null;
  41955. }
  41956. var scene = node.getScene();
  41957. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41958. };
  41959. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41960. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41961. if (!animation) {
  41962. return null;
  41963. }
  41964. node.animations.push(animation);
  41965. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41966. };
  41967. /**
  41968. * Transition property of the Camera to the target Value.
  41969. * @param property The property to transition
  41970. * @param targetValue The target Value of the property
  41971. * @param host The object where the property to animate belongs
  41972. * @param scene Scene used to run the animation
  41973. * @param frameRate Framerate (in frame/s) to use
  41974. * @param transition The transition type we want to use
  41975. * @param duration The duration of the animation, in milliseconds
  41976. * @param onAnimationEnd Call back trigger at the end of the animation.
  41977. */
  41978. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41979. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41980. if (duration <= 0) {
  41981. host[property] = targetValue;
  41982. if (onAnimationEnd) {
  41983. onAnimationEnd();
  41984. }
  41985. return null;
  41986. }
  41987. var endFrame = frameRate * (duration / 1000);
  41988. transition.setKeys([{
  41989. frame: 0,
  41990. value: host[property].clone ? host[property].clone() : host[property]
  41991. },
  41992. {
  41993. frame: endFrame,
  41994. value: targetValue
  41995. }]);
  41996. if (!host.animations) {
  41997. host.animations = [];
  41998. }
  41999. host.animations.push(transition);
  42000. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42001. animation.onAnimationEnd = onAnimationEnd;
  42002. return animation;
  42003. };
  42004. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42005. /**
  42006. * Return the array of runtime animations currently using this animation
  42007. */
  42008. get: function () {
  42009. return this._runtimeAnimations;
  42010. },
  42011. enumerable: true,
  42012. configurable: true
  42013. });
  42014. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42015. get: function () {
  42016. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42017. var runtimeAnimation = _a[_i];
  42018. if (!runtimeAnimation.isStopped) {
  42019. return true;
  42020. }
  42021. }
  42022. return false;
  42023. },
  42024. enumerable: true,
  42025. configurable: true
  42026. });
  42027. // Methods
  42028. /**
  42029. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42030. */
  42031. Animation.prototype.toString = function (fullDetails) {
  42032. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42033. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42034. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42035. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42036. if (fullDetails) {
  42037. ret += ", Ranges: {";
  42038. var first = true;
  42039. for (var name in this._ranges) {
  42040. if (first) {
  42041. ret += ", ";
  42042. first = false;
  42043. }
  42044. ret += name;
  42045. }
  42046. ret += "}";
  42047. }
  42048. return ret;
  42049. };
  42050. /**
  42051. * Add an event to this animation.
  42052. */
  42053. Animation.prototype.addEvent = function (event) {
  42054. this._events.push(event);
  42055. };
  42056. /**
  42057. * Remove all events found at the given frame
  42058. * @param frame
  42059. */
  42060. Animation.prototype.removeEvents = function (frame) {
  42061. for (var index = 0; index < this._events.length; index++) {
  42062. if (this._events[index].frame === frame) {
  42063. this._events.splice(index, 1);
  42064. index--;
  42065. }
  42066. }
  42067. };
  42068. Animation.prototype.getEvents = function () {
  42069. return this._events;
  42070. };
  42071. Animation.prototype.createRange = function (name, from, to) {
  42072. // check name not already in use; could happen for bones after serialized
  42073. if (!this._ranges[name]) {
  42074. this._ranges[name] = new AnimationRange(name, from, to);
  42075. }
  42076. };
  42077. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42078. if (deleteFrames === void 0) { deleteFrames = true; }
  42079. var range = this._ranges[name];
  42080. if (!range) {
  42081. return;
  42082. }
  42083. if (deleteFrames) {
  42084. var from = range.from;
  42085. var to = range.to;
  42086. // this loop MUST go high to low for multiple splices to work
  42087. for (var key = this._keys.length - 1; key >= 0; key--) {
  42088. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42089. this._keys.splice(key, 1);
  42090. }
  42091. }
  42092. }
  42093. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42094. };
  42095. Animation.prototype.getRange = function (name) {
  42096. return this._ranges[name];
  42097. };
  42098. Animation.prototype.getKeys = function () {
  42099. return this._keys;
  42100. };
  42101. Animation.prototype.getHighestFrame = function () {
  42102. var ret = 0;
  42103. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42104. if (ret < this._keys[key].frame) {
  42105. ret = this._keys[key].frame;
  42106. }
  42107. }
  42108. return ret;
  42109. };
  42110. Animation.prototype.getEasingFunction = function () {
  42111. return this._easingFunction;
  42112. };
  42113. Animation.prototype.setEasingFunction = function (easingFunction) {
  42114. this._easingFunction = easingFunction;
  42115. };
  42116. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42117. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42118. };
  42119. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42120. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42121. };
  42122. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42123. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42124. };
  42125. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42126. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42127. };
  42128. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42129. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42130. };
  42131. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42132. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42133. };
  42134. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42135. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42136. };
  42137. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42138. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42139. };
  42140. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42141. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42142. };
  42143. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42144. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42145. };
  42146. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42147. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42148. };
  42149. Animation.prototype.clone = function () {
  42150. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42151. clone.enableBlending = this.enableBlending;
  42152. clone.blendingSpeed = this.blendingSpeed;
  42153. if (this._keys) {
  42154. clone.setKeys(this._keys);
  42155. }
  42156. if (this._ranges) {
  42157. clone._ranges = {};
  42158. for (var name in this._ranges) {
  42159. var range = this._ranges[name];
  42160. if (!range) {
  42161. continue;
  42162. }
  42163. clone._ranges[name] = range.clone();
  42164. }
  42165. }
  42166. return clone;
  42167. };
  42168. Animation.prototype.setKeys = function (values) {
  42169. this._keys = values.slice(0);
  42170. };
  42171. Animation.prototype.serialize = function () {
  42172. var serializationObject = {};
  42173. serializationObject.name = this.name;
  42174. serializationObject.property = this.targetProperty;
  42175. serializationObject.framePerSecond = this.framePerSecond;
  42176. serializationObject.dataType = this.dataType;
  42177. serializationObject.loopBehavior = this.loopMode;
  42178. serializationObject.enableBlending = this.enableBlending;
  42179. serializationObject.blendingSpeed = this.blendingSpeed;
  42180. var dataType = this.dataType;
  42181. serializationObject.keys = [];
  42182. var keys = this.getKeys();
  42183. for (var index = 0; index < keys.length; index++) {
  42184. var animationKey = keys[index];
  42185. var key = {};
  42186. key.frame = animationKey.frame;
  42187. switch (dataType) {
  42188. case Animation.ANIMATIONTYPE_FLOAT:
  42189. key.values = [animationKey.value];
  42190. break;
  42191. case Animation.ANIMATIONTYPE_QUATERNION:
  42192. case Animation.ANIMATIONTYPE_MATRIX:
  42193. case Animation.ANIMATIONTYPE_VECTOR3:
  42194. case Animation.ANIMATIONTYPE_COLOR3:
  42195. key.values = animationKey.value.asArray();
  42196. break;
  42197. }
  42198. serializationObject.keys.push(key);
  42199. }
  42200. serializationObject.ranges = [];
  42201. for (var name in this._ranges) {
  42202. var source = this._ranges[name];
  42203. if (!source) {
  42204. continue;
  42205. }
  42206. var range = {};
  42207. range.name = name;
  42208. range.from = source.from;
  42209. range.to = source.to;
  42210. serializationObject.ranges.push(range);
  42211. }
  42212. return serializationObject;
  42213. };
  42214. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42215. get: function () {
  42216. return Animation._ANIMATIONTYPE_FLOAT;
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42222. get: function () {
  42223. return Animation._ANIMATIONTYPE_VECTOR3;
  42224. },
  42225. enumerable: true,
  42226. configurable: true
  42227. });
  42228. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42229. get: function () {
  42230. return Animation._ANIMATIONTYPE_VECTOR2;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42236. get: function () {
  42237. return Animation._ANIMATIONTYPE_SIZE;
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42243. get: function () {
  42244. return Animation._ANIMATIONTYPE_QUATERNION;
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42250. get: function () {
  42251. return Animation._ANIMATIONTYPE_MATRIX;
  42252. },
  42253. enumerable: true,
  42254. configurable: true
  42255. });
  42256. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42257. get: function () {
  42258. return Animation._ANIMATIONTYPE_COLOR3;
  42259. },
  42260. enumerable: true,
  42261. configurable: true
  42262. });
  42263. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42264. get: function () {
  42265. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42271. get: function () {
  42272. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42273. },
  42274. enumerable: true,
  42275. configurable: true
  42276. });
  42277. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42278. get: function () {
  42279. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. Animation.Parse = function (parsedAnimation) {
  42285. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42286. var dataType = parsedAnimation.dataType;
  42287. var keys = [];
  42288. var data;
  42289. var index;
  42290. if (parsedAnimation.enableBlending) {
  42291. animation.enableBlending = parsedAnimation.enableBlending;
  42292. }
  42293. if (parsedAnimation.blendingSpeed) {
  42294. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42295. }
  42296. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42297. var key = parsedAnimation.keys[index];
  42298. var inTangent;
  42299. var outTangent;
  42300. switch (dataType) {
  42301. case Animation.ANIMATIONTYPE_FLOAT:
  42302. data = key.values[0];
  42303. if (key.values.length >= 1) {
  42304. inTangent = key.values[1];
  42305. }
  42306. if (key.values.length >= 2) {
  42307. outTangent = key.values[2];
  42308. }
  42309. break;
  42310. case Animation.ANIMATIONTYPE_QUATERNION:
  42311. data = BABYLON.Quaternion.FromArray(key.values);
  42312. if (key.values.length >= 8) {
  42313. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42314. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42315. inTangent = _inTangent;
  42316. }
  42317. }
  42318. if (key.values.length >= 12) {
  42319. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42320. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42321. outTangent = _outTangent;
  42322. }
  42323. }
  42324. break;
  42325. case Animation.ANIMATIONTYPE_MATRIX:
  42326. data = BABYLON.Matrix.FromArray(key.values);
  42327. break;
  42328. case Animation.ANIMATIONTYPE_COLOR3:
  42329. data = BABYLON.Color3.FromArray(key.values);
  42330. break;
  42331. case Animation.ANIMATIONTYPE_VECTOR3:
  42332. default:
  42333. data = BABYLON.Vector3.FromArray(key.values);
  42334. break;
  42335. }
  42336. var keyData = {};
  42337. keyData.frame = key.frame;
  42338. keyData.value = data;
  42339. if (inTangent != undefined) {
  42340. keyData.inTangent = inTangent;
  42341. }
  42342. if (outTangent != undefined) {
  42343. keyData.outTangent = outTangent;
  42344. }
  42345. keys.push(keyData);
  42346. }
  42347. animation.setKeys(keys);
  42348. if (parsedAnimation.ranges) {
  42349. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42350. data = parsedAnimation.ranges[index];
  42351. animation.createRange(data.name, data.from, data.to);
  42352. }
  42353. }
  42354. return animation;
  42355. };
  42356. Animation.AppendSerializedAnimations = function (source, destination) {
  42357. if (source.animations) {
  42358. destination.animations = [];
  42359. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42360. var animation = source.animations[animationIndex];
  42361. destination.animations.push(animation.serialize());
  42362. }
  42363. }
  42364. };
  42365. Animation.AllowMatricesInterpolation = false;
  42366. // Statics
  42367. Animation._ANIMATIONTYPE_FLOAT = 0;
  42368. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42369. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42370. Animation._ANIMATIONTYPE_MATRIX = 3;
  42371. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42372. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42373. Animation._ANIMATIONTYPE_SIZE = 6;
  42374. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42375. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42376. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42377. return Animation;
  42378. }());
  42379. BABYLON.Animation = Animation;
  42380. })(BABYLON || (BABYLON = {}));
  42381. //# sourceMappingURL=babylon.animation.js.map
  42382. var BABYLON;
  42383. (function (BABYLON) {
  42384. /**
  42385. * This class defines the direct association between an animation and a target
  42386. */
  42387. var TargetedAnimation = /** @class */ (function () {
  42388. function TargetedAnimation() {
  42389. }
  42390. return TargetedAnimation;
  42391. }());
  42392. BABYLON.TargetedAnimation = TargetedAnimation;
  42393. /**
  42394. * Use this class to create coordinated animations on multiple targets
  42395. */
  42396. var AnimationGroup = /** @class */ (function () {
  42397. function AnimationGroup(name, scene) {
  42398. if (scene === void 0) { scene = null; }
  42399. this.name = name;
  42400. this._targetedAnimations = new Array();
  42401. this._animatables = new Array();
  42402. this._from = Number.MAX_VALUE;
  42403. this._to = Number.MIN_VALUE;
  42404. this._speedRatio = 1;
  42405. this.onAnimationEndObservable = new BABYLON.Observable();
  42406. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42407. this._scene.animationGroups.push(this);
  42408. }
  42409. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42410. /**
  42411. * Define if the animations are started
  42412. */
  42413. get: function () {
  42414. return this._isStarted;
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42420. /**
  42421. * Gets or sets the speed ratio to use for all animations
  42422. */
  42423. get: function () {
  42424. return this._speedRatio;
  42425. },
  42426. /**
  42427. * Gets or sets the speed ratio to use for all animations
  42428. */
  42429. set: function (value) {
  42430. if (this._speedRatio === value) {
  42431. return;
  42432. }
  42433. this._speedRatio = value;
  42434. for (var index = 0; index < this._animatables.length; index++) {
  42435. var animatable = this._animatables[index];
  42436. animatable.speedRatio = this._speedRatio;
  42437. }
  42438. },
  42439. enumerable: true,
  42440. configurable: true
  42441. });
  42442. /**
  42443. * Add an animation (with its target) in the group
  42444. * @param animation defines the animation we want to add
  42445. * @param target defines the target of the animation
  42446. * @returns the {BABYLON.TargetedAnimation} object
  42447. */
  42448. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42449. var targetedAnimation = {
  42450. animation: animation,
  42451. target: target
  42452. };
  42453. var keys = animation.getKeys();
  42454. if (this._from > keys[0].frame) {
  42455. this._from = keys[0].frame;
  42456. }
  42457. if (this._to < keys[keys.length - 1].frame) {
  42458. this._to = keys[keys.length - 1].frame;
  42459. }
  42460. this._targetedAnimations.push(targetedAnimation);
  42461. return targetedAnimation;
  42462. };
  42463. /**
  42464. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42465. * It can add constant keys at begin or end
  42466. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  42467. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  42468. */
  42469. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42470. beginFrame = Math.min(beginFrame, this._from);
  42471. endFrame = Math.min(endFrame, this._to);
  42472. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42473. var targetedAnimation = this._targetedAnimations[index];
  42474. var keys = targetedAnimation.animation.getKeys();
  42475. var startKey = keys[0];
  42476. var endKey = keys[keys.length - 1];
  42477. if (startKey.frame > beginFrame) {
  42478. var newKey = {
  42479. frame: beginFrame,
  42480. value: startKey.value,
  42481. inTangent: startKey.inTangent,
  42482. outTangent: startKey.outTangent
  42483. };
  42484. keys.splice(0, 0, newKey);
  42485. }
  42486. if (endKey.frame < endFrame) {
  42487. var newKey = {
  42488. frame: endFrame,
  42489. value: endKey.value,
  42490. inTangent: startKey.outTangent,
  42491. outTangent: startKey.outTangent
  42492. };
  42493. keys.push(newKey);
  42494. }
  42495. }
  42496. return this;
  42497. };
  42498. /**
  42499. * Start all animations on given targets
  42500. * @param loop defines if animations must loop
  42501. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42502. */
  42503. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42504. var _this = this;
  42505. if (loop === void 0) { loop = false; }
  42506. if (speedRatio === void 0) { speedRatio = 1; }
  42507. if (this._isStarted || this._targetedAnimations.length === 0) {
  42508. return this;
  42509. }
  42510. var _loop_1 = function () {
  42511. var targetedAnimation = this_1._targetedAnimations[index];
  42512. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42513. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42514. }));
  42515. };
  42516. var this_1 = this;
  42517. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42518. _loop_1();
  42519. }
  42520. this._speedRatio = speedRatio;
  42521. this._isStarted = true;
  42522. return this;
  42523. };
  42524. /**
  42525. * Pause all animations
  42526. */
  42527. AnimationGroup.prototype.pause = function () {
  42528. if (!this._isStarted) {
  42529. return this;
  42530. }
  42531. for (var index = 0; index < this._animatables.length; index++) {
  42532. var animatable = this._animatables[index];
  42533. animatable.pause();
  42534. }
  42535. return this;
  42536. };
  42537. /**
  42538. * Play all animations to initial state
  42539. * This function will start() the animations if they were not started or will restart() them if they were paused
  42540. * @param loop defines if animations must loop
  42541. */
  42542. AnimationGroup.prototype.play = function (loop) {
  42543. if (this.isStarted) {
  42544. if (loop !== undefined) {
  42545. for (var index = 0; index < this._animatables.length; index++) {
  42546. var animatable = this._animatables[index];
  42547. animatable.loopAnimation = loop;
  42548. }
  42549. }
  42550. this.restart();
  42551. }
  42552. else {
  42553. this.start(loop, this._speedRatio);
  42554. }
  42555. return this;
  42556. };
  42557. /**
  42558. * Reset all animations to initial state
  42559. */
  42560. AnimationGroup.prototype.reset = function () {
  42561. if (!this._isStarted) {
  42562. return this;
  42563. }
  42564. for (var index = 0; index < this._animatables.length; index++) {
  42565. var animatable = this._animatables[index];
  42566. animatable.reset();
  42567. }
  42568. return this;
  42569. };
  42570. /**
  42571. * Restart animations from key 0
  42572. */
  42573. AnimationGroup.prototype.restart = function () {
  42574. if (!this._isStarted) {
  42575. return this;
  42576. }
  42577. for (var index = 0; index < this._animatables.length; index++) {
  42578. var animatable = this._animatables[index];
  42579. animatable.restart();
  42580. }
  42581. return this;
  42582. };
  42583. /**
  42584. * Stop all animations
  42585. */
  42586. AnimationGroup.prototype.stop = function () {
  42587. if (!this._isStarted) {
  42588. return this;
  42589. }
  42590. for (var index = 0; index < this._animatables.length; index++) {
  42591. var animatable = this._animatables[index];
  42592. animatable.stop();
  42593. }
  42594. this._isStarted = false;
  42595. return this;
  42596. };
  42597. /**
  42598. * Dispose all associated resources
  42599. */
  42600. AnimationGroup.prototype.dispose = function () {
  42601. this._targetedAnimations = [];
  42602. this._animatables = [];
  42603. var index = this._scene.animationGroups.indexOf(this);
  42604. if (index > -1) {
  42605. this._scene.animationGroups.splice(index, 1);
  42606. }
  42607. };
  42608. return AnimationGroup;
  42609. }());
  42610. BABYLON.AnimationGroup = AnimationGroup;
  42611. })(BABYLON || (BABYLON = {}));
  42612. //# sourceMappingURL=babylon.animationGroup.js.map
  42613. var BABYLON;
  42614. (function (BABYLON) {
  42615. var RuntimeAnimation = /** @class */ (function () {
  42616. function RuntimeAnimation(target, animation) {
  42617. this._offsetsCache = {};
  42618. this._highLimitsCache = {};
  42619. this._stopped = false;
  42620. this._blendingFactor = 0;
  42621. this._ratioOffset = 0;
  42622. this._animation = animation;
  42623. this._target = target;
  42624. animation._runtimeAnimations.push(this);
  42625. }
  42626. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42627. get: function () {
  42628. return this._animation;
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. RuntimeAnimation.prototype.reset = function () {
  42634. this._offsetsCache = {};
  42635. this._highLimitsCache = {};
  42636. this.currentFrame = 0;
  42637. this._blendingFactor = 0;
  42638. this._originalBlendValue = null;
  42639. };
  42640. RuntimeAnimation.prototype.isStopped = function () {
  42641. return this._stopped;
  42642. };
  42643. RuntimeAnimation.prototype.dispose = function () {
  42644. var index = this._animation.runtimeAnimations.indexOf(this);
  42645. if (index > -1) {
  42646. this._animation.runtimeAnimations.splice(index, 1);
  42647. }
  42648. };
  42649. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42650. if (typeof value === "function") {
  42651. return value();
  42652. }
  42653. return value;
  42654. };
  42655. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42656. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42657. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42658. }
  42659. this.currentFrame = currentFrame;
  42660. var keys = this._animation.getKeys();
  42661. // Try to get a hash to find the right key
  42662. 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));
  42663. if (keys[startKeyIndex].frame >= currentFrame) {
  42664. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42665. startKeyIndex--;
  42666. }
  42667. }
  42668. for (var key = startKeyIndex; key < keys.length; key++) {
  42669. var endKey = keys[key + 1];
  42670. if (endKey.frame >= currentFrame) {
  42671. var startKey = keys[key];
  42672. var startValue = this._getKeyValue(startKey.value);
  42673. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42674. return startValue;
  42675. }
  42676. var endValue = this._getKeyValue(endKey.value);
  42677. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42678. var frameDelta = endKey.frame - startKey.frame;
  42679. // gradient : percent of currentFrame between the frame inf and the frame sup
  42680. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42681. // check for easingFunction and correction of gradient
  42682. var easingFunction = this._animation.getEasingFunction();
  42683. if (easingFunction != null) {
  42684. gradient = easingFunction.ease(gradient);
  42685. }
  42686. switch (this._animation.dataType) {
  42687. // Float
  42688. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42689. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42690. switch (loopMode) {
  42691. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42692. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42693. return floatValue;
  42694. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42695. return offsetValue * repeatCount + floatValue;
  42696. }
  42697. break;
  42698. // Quaternion
  42699. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42700. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42701. switch (loopMode) {
  42702. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42703. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42704. return quatValue;
  42705. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42706. return quatValue.add(offsetValue.scale(repeatCount));
  42707. }
  42708. return quatValue;
  42709. // Vector3
  42710. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42711. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42712. switch (loopMode) {
  42713. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42714. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42715. return vec3Value;
  42716. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42717. return vec3Value.add(offsetValue.scale(repeatCount));
  42718. }
  42719. // Vector2
  42720. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42721. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42722. switch (loopMode) {
  42723. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42724. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42725. return vec2Value;
  42726. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42727. return vec2Value.add(offsetValue.scale(repeatCount));
  42728. }
  42729. // Size
  42730. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42731. switch (loopMode) {
  42732. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42733. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42734. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42735. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42736. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42737. }
  42738. // Color3
  42739. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42740. switch (loopMode) {
  42741. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42742. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42743. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42744. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42745. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42746. }
  42747. // Matrix
  42748. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42749. switch (loopMode) {
  42750. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42751. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42752. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42753. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42754. }
  42755. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42756. return startValue;
  42757. }
  42758. default:
  42759. break;
  42760. }
  42761. break;
  42762. }
  42763. }
  42764. return this._getKeyValue(keys[keys.length - 1].value);
  42765. };
  42766. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42767. if (blend === void 0) { blend = false; }
  42768. // Set value
  42769. var path;
  42770. var destination;
  42771. var targetPropertyPath = this._animation.targetPropertyPath;
  42772. if (targetPropertyPath.length > 1) {
  42773. var property = this._target[targetPropertyPath[0]];
  42774. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42775. property = property[targetPropertyPath[index]];
  42776. }
  42777. path = targetPropertyPath[targetPropertyPath.length - 1];
  42778. destination = property;
  42779. }
  42780. else {
  42781. path = targetPropertyPath[0];
  42782. destination = this._target;
  42783. }
  42784. // Blending
  42785. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42786. if (!this._originalBlendValue) {
  42787. if (destination[path].clone) {
  42788. this._originalBlendValue = destination[path].clone();
  42789. }
  42790. else {
  42791. this._originalBlendValue = destination[path];
  42792. }
  42793. }
  42794. if (this._originalBlendValue.prototype) {
  42795. if (this._originalBlendValue.prototype.Lerp) {
  42796. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42797. }
  42798. else {
  42799. destination[path] = currentValue;
  42800. }
  42801. }
  42802. else if (this._originalBlendValue.m) {
  42803. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42804. }
  42805. else {
  42806. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42807. }
  42808. this._blendingFactor += this._animation.blendingSpeed;
  42809. }
  42810. else {
  42811. destination[path] = currentValue;
  42812. }
  42813. if (this._target.markAsDirty) {
  42814. this._target.markAsDirty(this._animation.targetProperty);
  42815. }
  42816. };
  42817. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42818. var keys = this._animation.getKeys();
  42819. if (frame < keys[0].frame) {
  42820. frame = keys[0].frame;
  42821. }
  42822. else if (frame > keys[keys.length - 1].frame) {
  42823. frame = keys[keys.length - 1].frame;
  42824. }
  42825. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42826. this.setValue(currentValue);
  42827. };
  42828. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42829. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42830. this._ratioOffset = this._previousRatio - newRatio;
  42831. };
  42832. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42833. if (blend === void 0) { blend = false; }
  42834. var targetPropertyPath = this._animation.targetPropertyPath;
  42835. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42836. this._stopped = true;
  42837. return false;
  42838. }
  42839. var returnValue = true;
  42840. var keys = this._animation.getKeys();
  42841. // Adding a start key at frame 0 if missing
  42842. if (keys[0].frame !== 0) {
  42843. var newKey = { frame: 0, value: keys[0].value };
  42844. keys.splice(0, 0, newKey);
  42845. }
  42846. // Check limits
  42847. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42848. from = keys[0].frame;
  42849. }
  42850. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42851. to = keys[keys.length - 1].frame;
  42852. }
  42853. //to and from cannot be the same key
  42854. if (from === to) {
  42855. if (from > keys[0].frame) {
  42856. from--;
  42857. }
  42858. else if (to < keys[keys.length - 1].frame) {
  42859. to++;
  42860. }
  42861. }
  42862. // Compute ratio
  42863. var range = to - from;
  42864. var offsetValue;
  42865. // ratio represents the frame delta between from and to
  42866. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42867. var highLimitValue = 0;
  42868. this._previousDelay = delay;
  42869. this._previousRatio = ratio;
  42870. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42871. returnValue = false;
  42872. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42873. }
  42874. else {
  42875. // Get max value if required
  42876. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42877. var keyOffset = to.toString() + from.toString();
  42878. if (!this._offsetsCache[keyOffset]) {
  42879. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42880. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42881. switch (this._animation.dataType) {
  42882. // Float
  42883. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42884. this._offsetsCache[keyOffset] = toValue - fromValue;
  42885. break;
  42886. // Quaternion
  42887. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42888. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42889. break;
  42890. // Vector3
  42891. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42892. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42893. // Vector2
  42894. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42895. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42896. // Size
  42897. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42898. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42899. // Color3
  42900. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42901. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42902. default:
  42903. break;
  42904. }
  42905. this._highLimitsCache[keyOffset] = toValue;
  42906. }
  42907. highLimitValue = this._highLimitsCache[keyOffset];
  42908. offsetValue = this._offsetsCache[keyOffset];
  42909. }
  42910. }
  42911. if (offsetValue === undefined) {
  42912. switch (this._animation.dataType) {
  42913. // Float
  42914. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42915. offsetValue = 0;
  42916. break;
  42917. // Quaternion
  42918. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42919. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42920. break;
  42921. // Vector3
  42922. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42923. offsetValue = BABYLON.Vector3.Zero();
  42924. break;
  42925. // Vector2
  42926. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42927. offsetValue = BABYLON.Vector2.Zero();
  42928. break;
  42929. // Size
  42930. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42931. offsetValue = BABYLON.Size.Zero();
  42932. break;
  42933. // Color3
  42934. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42935. offsetValue = BABYLON.Color3.Black();
  42936. }
  42937. }
  42938. // Compute value
  42939. var repeatCount = (ratio / range) >> 0;
  42940. var currentFrame = returnValue ? from + ratio % range : to;
  42941. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42942. // Set value
  42943. this.setValue(currentValue);
  42944. // Check events
  42945. var events = this._animation.getEvents();
  42946. for (var index = 0; index < events.length; index++) {
  42947. // Make sure current frame has passed event frame and that event frame is within the current range
  42948. // Also, handle both forward and reverse animations
  42949. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42950. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42951. var event = events[index];
  42952. if (!event.isDone) {
  42953. // If event should be done only once, remove it.
  42954. if (event.onlyOnce) {
  42955. events.splice(index, 1);
  42956. index--;
  42957. }
  42958. event.isDone = true;
  42959. event.action();
  42960. } // Don't do anything if the event has already be done.
  42961. }
  42962. else if (events[index].isDone && !events[index].onlyOnce) {
  42963. // reset event, the animation is looping
  42964. events[index].isDone = false;
  42965. }
  42966. }
  42967. if (!returnValue) {
  42968. this._stopped = true;
  42969. }
  42970. return returnValue;
  42971. };
  42972. return RuntimeAnimation;
  42973. }());
  42974. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42975. })(BABYLON || (BABYLON = {}));
  42976. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42977. var BABYLON;
  42978. (function (BABYLON) {
  42979. var Animatable = /** @class */ (function () {
  42980. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42981. if (fromFrame === void 0) { fromFrame = 0; }
  42982. if (toFrame === void 0) { toFrame = 100; }
  42983. if (loopAnimation === void 0) { loopAnimation = false; }
  42984. if (speedRatio === void 0) { speedRatio = 1.0; }
  42985. this.target = target;
  42986. this.fromFrame = fromFrame;
  42987. this.toFrame = toFrame;
  42988. this.loopAnimation = loopAnimation;
  42989. this.onAnimationEnd = onAnimationEnd;
  42990. this._localDelayOffset = null;
  42991. this._pausedDelay = null;
  42992. this._runtimeAnimations = new Array();
  42993. this._paused = false;
  42994. this._speedRatio = 1;
  42995. this.animationStarted = false;
  42996. if (animations) {
  42997. this.appendAnimations(target, animations);
  42998. }
  42999. this._speedRatio = speedRatio;
  43000. this._scene = scene;
  43001. scene._activeAnimatables.push(this);
  43002. }
  43003. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43004. get: function () {
  43005. return this._speedRatio;
  43006. },
  43007. set: function (value) {
  43008. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43009. var animation = this._runtimeAnimations[index];
  43010. animation._prepareForSpeedRatioChange(value);
  43011. }
  43012. this._speedRatio = value;
  43013. },
  43014. enumerable: true,
  43015. configurable: true
  43016. });
  43017. // Methods
  43018. Animatable.prototype.getAnimations = function () {
  43019. return this._runtimeAnimations;
  43020. };
  43021. Animatable.prototype.appendAnimations = function (target, animations) {
  43022. for (var index = 0; index < animations.length; index++) {
  43023. var animation = animations[index];
  43024. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43025. }
  43026. };
  43027. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43028. var runtimeAnimations = this._runtimeAnimations;
  43029. for (var index = 0; index < runtimeAnimations.length; index++) {
  43030. if (runtimeAnimations[index].animation.targetProperty === property) {
  43031. return runtimeAnimations[index].animation;
  43032. }
  43033. }
  43034. return null;
  43035. };
  43036. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43037. var runtimeAnimations = this._runtimeAnimations;
  43038. for (var index = 0; index < runtimeAnimations.length; index++) {
  43039. if (runtimeAnimations[index].animation.targetProperty === property) {
  43040. return runtimeAnimations[index];
  43041. }
  43042. }
  43043. return null;
  43044. };
  43045. Animatable.prototype.reset = function () {
  43046. var runtimeAnimations = this._runtimeAnimations;
  43047. for (var index = 0; index < runtimeAnimations.length; index++) {
  43048. runtimeAnimations[index].reset();
  43049. }
  43050. // Reset to original value
  43051. for (index = 0; index < runtimeAnimations.length; index++) {
  43052. var animation = runtimeAnimations[index];
  43053. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43054. }
  43055. this._localDelayOffset = null;
  43056. this._pausedDelay = null;
  43057. };
  43058. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43059. var runtimeAnimations = this._runtimeAnimations;
  43060. for (var index = 0; index < runtimeAnimations.length; index++) {
  43061. runtimeAnimations[index].animation.enableBlending = true;
  43062. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43063. }
  43064. };
  43065. Animatable.prototype.disableBlending = function () {
  43066. var runtimeAnimations = this._runtimeAnimations;
  43067. for (var index = 0; index < runtimeAnimations.length; index++) {
  43068. runtimeAnimations[index].animation.enableBlending = false;
  43069. }
  43070. };
  43071. Animatable.prototype.goToFrame = function (frame) {
  43072. var runtimeAnimations = this._runtimeAnimations;
  43073. if (runtimeAnimations[0]) {
  43074. var fps = runtimeAnimations[0].animation.framePerSecond;
  43075. var currentFrame = runtimeAnimations[0].currentFrame;
  43076. var adjustTime = frame - currentFrame;
  43077. var delay = adjustTime * 1000 / fps;
  43078. if (this._localDelayOffset === null) {
  43079. this._localDelayOffset = 0;
  43080. }
  43081. this._localDelayOffset -= delay;
  43082. }
  43083. for (var index = 0; index < runtimeAnimations.length; index++) {
  43084. runtimeAnimations[index].goToFrame(frame);
  43085. }
  43086. };
  43087. Animatable.prototype.pause = function () {
  43088. if (this._paused) {
  43089. return;
  43090. }
  43091. this._paused = true;
  43092. };
  43093. Animatable.prototype.restart = function () {
  43094. this._paused = false;
  43095. };
  43096. Animatable.prototype.stop = function (animationName) {
  43097. if (animationName) {
  43098. var idx = this._scene._activeAnimatables.indexOf(this);
  43099. if (idx > -1) {
  43100. var runtimeAnimations = this._runtimeAnimations;
  43101. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43102. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43103. continue;
  43104. }
  43105. runtimeAnimations[index].dispose();
  43106. runtimeAnimations.splice(index, 1);
  43107. }
  43108. if (runtimeAnimations.length == 0) {
  43109. this._scene._activeAnimatables.splice(idx, 1);
  43110. if (this.onAnimationEnd) {
  43111. this.onAnimationEnd();
  43112. }
  43113. }
  43114. }
  43115. }
  43116. else {
  43117. var index = this._scene._activeAnimatables.indexOf(this);
  43118. if (index > -1) {
  43119. this._scene._activeAnimatables.splice(index, 1);
  43120. var runtimeAnimations = this._runtimeAnimations;
  43121. for (var index = 0; index < runtimeAnimations.length; index++) {
  43122. runtimeAnimations[index].dispose();
  43123. }
  43124. if (this.onAnimationEnd) {
  43125. this.onAnimationEnd();
  43126. }
  43127. }
  43128. }
  43129. };
  43130. Animatable.prototype._animate = function (delay) {
  43131. if (this._paused) {
  43132. this.animationStarted = false;
  43133. if (this._pausedDelay === null) {
  43134. this._pausedDelay = delay;
  43135. }
  43136. return true;
  43137. }
  43138. if (this._localDelayOffset === null) {
  43139. this._localDelayOffset = delay;
  43140. }
  43141. else if (this._pausedDelay !== null) {
  43142. this._localDelayOffset += delay - this._pausedDelay;
  43143. this._pausedDelay = null;
  43144. }
  43145. // Animating
  43146. var running = false;
  43147. var runtimeAnimations = this._runtimeAnimations;
  43148. var index;
  43149. for (index = 0; index < runtimeAnimations.length; index++) {
  43150. var animation = runtimeAnimations[index];
  43151. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43152. running = running || isRunning;
  43153. }
  43154. this.animationStarted = running;
  43155. if (!running) {
  43156. // Remove from active animatables
  43157. index = this._scene._activeAnimatables.indexOf(this);
  43158. this._scene._activeAnimatables.splice(index, 1);
  43159. // Dispose all runtime animations
  43160. for (index = 0; index < runtimeAnimations.length; index++) {
  43161. runtimeAnimations[index].dispose();
  43162. }
  43163. }
  43164. if (!running && this.onAnimationEnd) {
  43165. this.onAnimationEnd();
  43166. this.onAnimationEnd = null;
  43167. }
  43168. return running;
  43169. };
  43170. return Animatable;
  43171. }());
  43172. BABYLON.Animatable = Animatable;
  43173. })(BABYLON || (BABYLON = {}));
  43174. //# sourceMappingURL=babylon.animatable.js.map
  43175. var BABYLON;
  43176. (function (BABYLON) {
  43177. var EasingFunction = /** @class */ (function () {
  43178. function EasingFunction() {
  43179. // Properties
  43180. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43181. }
  43182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43183. get: function () {
  43184. return EasingFunction._EASINGMODE_EASEIN;
  43185. },
  43186. enumerable: true,
  43187. configurable: true
  43188. });
  43189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43190. get: function () {
  43191. return EasingFunction._EASINGMODE_EASEOUT;
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43197. get: function () {
  43198. return EasingFunction._EASINGMODE_EASEINOUT;
  43199. },
  43200. enumerable: true,
  43201. configurable: true
  43202. });
  43203. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43204. var n = Math.min(Math.max(easingMode, 0), 2);
  43205. this._easingMode = n;
  43206. };
  43207. EasingFunction.prototype.getEasingMode = function () {
  43208. return this._easingMode;
  43209. };
  43210. EasingFunction.prototype.easeInCore = function (gradient) {
  43211. throw new Error('You must implement this method');
  43212. };
  43213. EasingFunction.prototype.ease = function (gradient) {
  43214. switch (this._easingMode) {
  43215. case EasingFunction.EASINGMODE_EASEIN:
  43216. return this.easeInCore(gradient);
  43217. case EasingFunction.EASINGMODE_EASEOUT:
  43218. return (1 - this.easeInCore(1 - gradient));
  43219. }
  43220. if (gradient >= 0.5) {
  43221. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43222. }
  43223. return (this.easeInCore(gradient * 2) * 0.5);
  43224. };
  43225. //Statics
  43226. EasingFunction._EASINGMODE_EASEIN = 0;
  43227. EasingFunction._EASINGMODE_EASEOUT = 1;
  43228. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43229. return EasingFunction;
  43230. }());
  43231. BABYLON.EasingFunction = EasingFunction;
  43232. var CircleEase = /** @class */ (function (_super) {
  43233. __extends(CircleEase, _super);
  43234. function CircleEase() {
  43235. return _super !== null && _super.apply(this, arguments) || this;
  43236. }
  43237. CircleEase.prototype.easeInCore = function (gradient) {
  43238. gradient = Math.max(0, Math.min(1, gradient));
  43239. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43240. };
  43241. return CircleEase;
  43242. }(EasingFunction));
  43243. BABYLON.CircleEase = CircleEase;
  43244. var BackEase = /** @class */ (function (_super) {
  43245. __extends(BackEase, _super);
  43246. function BackEase(amplitude) {
  43247. if (amplitude === void 0) { amplitude = 1; }
  43248. var _this = _super.call(this) || this;
  43249. _this.amplitude = amplitude;
  43250. return _this;
  43251. }
  43252. BackEase.prototype.easeInCore = function (gradient) {
  43253. var num = Math.max(0, this.amplitude);
  43254. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43255. };
  43256. return BackEase;
  43257. }(EasingFunction));
  43258. BABYLON.BackEase = BackEase;
  43259. var BounceEase = /** @class */ (function (_super) {
  43260. __extends(BounceEase, _super);
  43261. function BounceEase(bounces, bounciness) {
  43262. if (bounces === void 0) { bounces = 3; }
  43263. if (bounciness === void 0) { bounciness = 2; }
  43264. var _this = _super.call(this) || this;
  43265. _this.bounces = bounces;
  43266. _this.bounciness = bounciness;
  43267. return _this;
  43268. }
  43269. BounceEase.prototype.easeInCore = function (gradient) {
  43270. var y = Math.max(0.0, this.bounces);
  43271. var bounciness = this.bounciness;
  43272. if (bounciness <= 1.0) {
  43273. bounciness = 1.001;
  43274. }
  43275. var num9 = Math.pow(bounciness, y);
  43276. var num5 = 1.0 - bounciness;
  43277. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43278. var num15 = gradient * num4;
  43279. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43280. var num3 = Math.floor(num65);
  43281. var num13 = num3 + 1.0;
  43282. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43283. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43284. var num7 = (num8 + num12) * 0.5;
  43285. var num6 = gradient - num7;
  43286. var num2 = num7 - num8;
  43287. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43288. };
  43289. return BounceEase;
  43290. }(EasingFunction));
  43291. BABYLON.BounceEase = BounceEase;
  43292. var CubicEase = /** @class */ (function (_super) {
  43293. __extends(CubicEase, _super);
  43294. function CubicEase() {
  43295. return _super !== null && _super.apply(this, arguments) || this;
  43296. }
  43297. CubicEase.prototype.easeInCore = function (gradient) {
  43298. return (gradient * gradient * gradient);
  43299. };
  43300. return CubicEase;
  43301. }(EasingFunction));
  43302. BABYLON.CubicEase = CubicEase;
  43303. var ElasticEase = /** @class */ (function (_super) {
  43304. __extends(ElasticEase, _super);
  43305. function ElasticEase(oscillations, springiness) {
  43306. if (oscillations === void 0) { oscillations = 3; }
  43307. if (springiness === void 0) { springiness = 3; }
  43308. var _this = _super.call(this) || this;
  43309. _this.oscillations = oscillations;
  43310. _this.springiness = springiness;
  43311. return _this;
  43312. }
  43313. ElasticEase.prototype.easeInCore = function (gradient) {
  43314. var num2;
  43315. var num3 = Math.max(0.0, this.oscillations);
  43316. var num = Math.max(0.0, this.springiness);
  43317. if (num == 0) {
  43318. num2 = gradient;
  43319. }
  43320. else {
  43321. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43322. }
  43323. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43324. };
  43325. return ElasticEase;
  43326. }(EasingFunction));
  43327. BABYLON.ElasticEase = ElasticEase;
  43328. var ExponentialEase = /** @class */ (function (_super) {
  43329. __extends(ExponentialEase, _super);
  43330. function ExponentialEase(exponent) {
  43331. if (exponent === void 0) { exponent = 2; }
  43332. var _this = _super.call(this) || this;
  43333. _this.exponent = exponent;
  43334. return _this;
  43335. }
  43336. ExponentialEase.prototype.easeInCore = function (gradient) {
  43337. if (this.exponent <= 0) {
  43338. return gradient;
  43339. }
  43340. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43341. };
  43342. return ExponentialEase;
  43343. }(EasingFunction));
  43344. BABYLON.ExponentialEase = ExponentialEase;
  43345. var PowerEase = /** @class */ (function (_super) {
  43346. __extends(PowerEase, _super);
  43347. function PowerEase(power) {
  43348. if (power === void 0) { power = 2; }
  43349. var _this = _super.call(this) || this;
  43350. _this.power = power;
  43351. return _this;
  43352. }
  43353. PowerEase.prototype.easeInCore = function (gradient) {
  43354. var y = Math.max(0.0, this.power);
  43355. return Math.pow(gradient, y);
  43356. };
  43357. return PowerEase;
  43358. }(EasingFunction));
  43359. BABYLON.PowerEase = PowerEase;
  43360. var QuadraticEase = /** @class */ (function (_super) {
  43361. __extends(QuadraticEase, _super);
  43362. function QuadraticEase() {
  43363. return _super !== null && _super.apply(this, arguments) || this;
  43364. }
  43365. QuadraticEase.prototype.easeInCore = function (gradient) {
  43366. return (gradient * gradient);
  43367. };
  43368. return QuadraticEase;
  43369. }(EasingFunction));
  43370. BABYLON.QuadraticEase = QuadraticEase;
  43371. var QuarticEase = /** @class */ (function (_super) {
  43372. __extends(QuarticEase, _super);
  43373. function QuarticEase() {
  43374. return _super !== null && _super.apply(this, arguments) || this;
  43375. }
  43376. QuarticEase.prototype.easeInCore = function (gradient) {
  43377. return (gradient * gradient * gradient * gradient);
  43378. };
  43379. return QuarticEase;
  43380. }(EasingFunction));
  43381. BABYLON.QuarticEase = QuarticEase;
  43382. var QuinticEase = /** @class */ (function (_super) {
  43383. __extends(QuinticEase, _super);
  43384. function QuinticEase() {
  43385. return _super !== null && _super.apply(this, arguments) || this;
  43386. }
  43387. QuinticEase.prototype.easeInCore = function (gradient) {
  43388. return (gradient * gradient * gradient * gradient * gradient);
  43389. };
  43390. return QuinticEase;
  43391. }(EasingFunction));
  43392. BABYLON.QuinticEase = QuinticEase;
  43393. var SineEase = /** @class */ (function (_super) {
  43394. __extends(SineEase, _super);
  43395. function SineEase() {
  43396. return _super !== null && _super.apply(this, arguments) || this;
  43397. }
  43398. SineEase.prototype.easeInCore = function (gradient) {
  43399. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43400. };
  43401. return SineEase;
  43402. }(EasingFunction));
  43403. BABYLON.SineEase = SineEase;
  43404. var BezierCurveEase = /** @class */ (function (_super) {
  43405. __extends(BezierCurveEase, _super);
  43406. function BezierCurveEase(x1, y1, x2, y2) {
  43407. if (x1 === void 0) { x1 = 0; }
  43408. if (y1 === void 0) { y1 = 0; }
  43409. if (x2 === void 0) { x2 = 1; }
  43410. if (y2 === void 0) { y2 = 1; }
  43411. var _this = _super.call(this) || this;
  43412. _this.x1 = x1;
  43413. _this.y1 = y1;
  43414. _this.x2 = x2;
  43415. _this.y2 = y2;
  43416. return _this;
  43417. }
  43418. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43419. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43420. };
  43421. return BezierCurveEase;
  43422. }(EasingFunction));
  43423. BABYLON.BezierCurveEase = BezierCurveEase;
  43424. })(BABYLON || (BABYLON = {}));
  43425. //# sourceMappingURL=babylon.easing.js.map
  43426. var BABYLON;
  43427. (function (BABYLON) {
  43428. var Condition = /** @class */ (function () {
  43429. function Condition(actionManager) {
  43430. this._actionManager = actionManager;
  43431. }
  43432. Condition.prototype.isValid = function () {
  43433. return true;
  43434. };
  43435. Condition.prototype._getProperty = function (propertyPath) {
  43436. return this._actionManager._getProperty(propertyPath);
  43437. };
  43438. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43439. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43440. };
  43441. Condition.prototype.serialize = function () {
  43442. };
  43443. Condition.prototype._serialize = function (serializedCondition) {
  43444. return {
  43445. type: 2,
  43446. children: [],
  43447. name: serializedCondition.name,
  43448. properties: serializedCondition.properties
  43449. };
  43450. };
  43451. return Condition;
  43452. }());
  43453. BABYLON.Condition = Condition;
  43454. var ValueCondition = /** @class */ (function (_super) {
  43455. __extends(ValueCondition, _super);
  43456. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43457. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43458. var _this = _super.call(this, actionManager) || this;
  43459. _this.propertyPath = propertyPath;
  43460. _this.value = value;
  43461. _this.operator = operator;
  43462. _this._target = target;
  43463. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43464. _this._property = _this._getProperty(_this.propertyPath);
  43465. return _this;
  43466. }
  43467. Object.defineProperty(ValueCondition, "IsEqual", {
  43468. get: function () {
  43469. return ValueCondition._IsEqual;
  43470. },
  43471. enumerable: true,
  43472. configurable: true
  43473. });
  43474. Object.defineProperty(ValueCondition, "IsDifferent", {
  43475. get: function () {
  43476. return ValueCondition._IsDifferent;
  43477. },
  43478. enumerable: true,
  43479. configurable: true
  43480. });
  43481. Object.defineProperty(ValueCondition, "IsGreater", {
  43482. get: function () {
  43483. return ValueCondition._IsGreater;
  43484. },
  43485. enumerable: true,
  43486. configurable: true
  43487. });
  43488. Object.defineProperty(ValueCondition, "IsLesser", {
  43489. get: function () {
  43490. return ValueCondition._IsLesser;
  43491. },
  43492. enumerable: true,
  43493. configurable: true
  43494. });
  43495. // Methods
  43496. ValueCondition.prototype.isValid = function () {
  43497. switch (this.operator) {
  43498. case ValueCondition.IsGreater:
  43499. return this._effectiveTarget[this._property] > this.value;
  43500. case ValueCondition.IsLesser:
  43501. return this._effectiveTarget[this._property] < this.value;
  43502. case ValueCondition.IsEqual:
  43503. case ValueCondition.IsDifferent:
  43504. var check;
  43505. if (this.value.equals) {
  43506. check = this.value.equals(this._effectiveTarget[this._property]);
  43507. }
  43508. else {
  43509. check = this.value === this._effectiveTarget[this._property];
  43510. }
  43511. return this.operator === ValueCondition.IsEqual ? check : !check;
  43512. }
  43513. return false;
  43514. };
  43515. ValueCondition.prototype.serialize = function () {
  43516. return this._serialize({
  43517. name: "ValueCondition",
  43518. properties: [
  43519. BABYLON.Action._GetTargetProperty(this._target),
  43520. { name: "propertyPath", value: this.propertyPath },
  43521. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43522. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43523. ]
  43524. });
  43525. };
  43526. ValueCondition.GetOperatorName = function (operator) {
  43527. switch (operator) {
  43528. case ValueCondition._IsEqual: return "IsEqual";
  43529. case ValueCondition._IsDifferent: return "IsDifferent";
  43530. case ValueCondition._IsGreater: return "IsGreater";
  43531. case ValueCondition._IsLesser: return "IsLesser";
  43532. default: return "";
  43533. }
  43534. };
  43535. // Statics
  43536. ValueCondition._IsEqual = 0;
  43537. ValueCondition._IsDifferent = 1;
  43538. ValueCondition._IsGreater = 2;
  43539. ValueCondition._IsLesser = 3;
  43540. return ValueCondition;
  43541. }(Condition));
  43542. BABYLON.ValueCondition = ValueCondition;
  43543. var PredicateCondition = /** @class */ (function (_super) {
  43544. __extends(PredicateCondition, _super);
  43545. function PredicateCondition(actionManager, predicate) {
  43546. var _this = _super.call(this, actionManager) || this;
  43547. _this.predicate = predicate;
  43548. return _this;
  43549. }
  43550. PredicateCondition.prototype.isValid = function () {
  43551. return this.predicate();
  43552. };
  43553. return PredicateCondition;
  43554. }(Condition));
  43555. BABYLON.PredicateCondition = PredicateCondition;
  43556. var StateCondition = /** @class */ (function (_super) {
  43557. __extends(StateCondition, _super);
  43558. function StateCondition(actionManager, target, value) {
  43559. var _this = _super.call(this, actionManager) || this;
  43560. _this.value = value;
  43561. _this._target = target;
  43562. return _this;
  43563. }
  43564. // Methods
  43565. StateCondition.prototype.isValid = function () {
  43566. return this._target.state === this.value;
  43567. };
  43568. StateCondition.prototype.serialize = function () {
  43569. return this._serialize({
  43570. name: "StateCondition",
  43571. properties: [
  43572. BABYLON.Action._GetTargetProperty(this._target),
  43573. { name: "value", value: this.value }
  43574. ]
  43575. });
  43576. };
  43577. return StateCondition;
  43578. }(Condition));
  43579. BABYLON.StateCondition = StateCondition;
  43580. })(BABYLON || (BABYLON = {}));
  43581. //# sourceMappingURL=babylon.condition.js.map
  43582. var BABYLON;
  43583. (function (BABYLON) {
  43584. var Action = /** @class */ (function () {
  43585. function Action(triggerOptions, condition) {
  43586. this.triggerOptions = triggerOptions;
  43587. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43588. if (triggerOptions.parameter) {
  43589. this.trigger = triggerOptions.trigger;
  43590. this._triggerParameter = triggerOptions.parameter;
  43591. }
  43592. else {
  43593. this.trigger = triggerOptions;
  43594. }
  43595. this._nextActiveAction = this;
  43596. this._condition = condition;
  43597. }
  43598. // Methods
  43599. Action.prototype._prepare = function () {
  43600. };
  43601. Action.prototype.getTriggerParameter = function () {
  43602. return this._triggerParameter;
  43603. };
  43604. Action.prototype._executeCurrent = function (evt) {
  43605. if (this._nextActiveAction._condition) {
  43606. var condition = this._nextActiveAction._condition;
  43607. var currentRenderId = this._actionManager.getScene().getRenderId();
  43608. // We cache the current evaluation for the current frame
  43609. if (condition._evaluationId === currentRenderId) {
  43610. if (!condition._currentResult) {
  43611. return;
  43612. }
  43613. }
  43614. else {
  43615. condition._evaluationId = currentRenderId;
  43616. if (!condition.isValid()) {
  43617. condition._currentResult = false;
  43618. return;
  43619. }
  43620. condition._currentResult = true;
  43621. }
  43622. }
  43623. this.onBeforeExecuteObservable.notifyObservers(this);
  43624. this._nextActiveAction.execute(evt);
  43625. this.skipToNextActiveAction();
  43626. };
  43627. Action.prototype.execute = function (evt) {
  43628. };
  43629. Action.prototype.skipToNextActiveAction = function () {
  43630. if (this._nextActiveAction._child) {
  43631. if (!this._nextActiveAction._child._actionManager) {
  43632. this._nextActiveAction._child._actionManager = this._actionManager;
  43633. }
  43634. this._nextActiveAction = this._nextActiveAction._child;
  43635. }
  43636. else {
  43637. this._nextActiveAction = this;
  43638. }
  43639. };
  43640. Action.prototype.then = function (action) {
  43641. this._child = action;
  43642. action._actionManager = this._actionManager;
  43643. action._prepare();
  43644. return action;
  43645. };
  43646. Action.prototype._getProperty = function (propertyPath) {
  43647. return this._actionManager._getProperty(propertyPath);
  43648. };
  43649. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43650. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43651. };
  43652. Action.prototype.serialize = function (parent) {
  43653. };
  43654. // Called by BABYLON.Action objects in serialize(...). Internal use
  43655. Action.prototype._serialize = function (serializedAction, parent) {
  43656. var serializationObject = {
  43657. type: 1,
  43658. children: [],
  43659. name: serializedAction.name,
  43660. properties: serializedAction.properties || []
  43661. };
  43662. // Serialize child
  43663. if (this._child) {
  43664. this._child.serialize(serializationObject);
  43665. }
  43666. // Check if "this" has a condition
  43667. if (this._condition) {
  43668. var serializedCondition = this._condition.serialize();
  43669. serializedCondition.children.push(serializationObject);
  43670. if (parent) {
  43671. parent.children.push(serializedCondition);
  43672. }
  43673. return serializedCondition;
  43674. }
  43675. if (parent) {
  43676. parent.children.push(serializationObject);
  43677. }
  43678. return serializationObject;
  43679. };
  43680. Action._SerializeValueAsString = function (value) {
  43681. if (typeof value === "number") {
  43682. return value.toString();
  43683. }
  43684. if (typeof value === "boolean") {
  43685. return value ? "true" : "false";
  43686. }
  43687. if (value instanceof BABYLON.Vector2) {
  43688. return value.x + ", " + value.y;
  43689. }
  43690. if (value instanceof BABYLON.Vector3) {
  43691. return value.x + ", " + value.y + ", " + value.z;
  43692. }
  43693. if (value instanceof BABYLON.Color3) {
  43694. return value.r + ", " + value.g + ", " + value.b;
  43695. }
  43696. if (value instanceof BABYLON.Color4) {
  43697. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43698. }
  43699. return value; // string
  43700. };
  43701. Action._GetTargetProperty = function (target) {
  43702. return {
  43703. name: "target",
  43704. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43705. : target instanceof BABYLON.Light ? "LightProperties"
  43706. : target instanceof BABYLON.Camera ? "CameraProperties"
  43707. : "SceneProperties",
  43708. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43709. };
  43710. };
  43711. return Action;
  43712. }());
  43713. BABYLON.Action = Action;
  43714. })(BABYLON || (BABYLON = {}));
  43715. //# sourceMappingURL=babylon.action.js.map
  43716. var BABYLON;
  43717. (function (BABYLON) {
  43718. /**
  43719. * ActionEvent is the event beint sent when an action is triggered.
  43720. */
  43721. var ActionEvent = /** @class */ (function () {
  43722. /**
  43723. * @param source The mesh or sprite that triggered the action.
  43724. * @param pointerX The X mouse cursor position at the time of the event
  43725. * @param pointerY The Y mouse cursor position at the time of the event
  43726. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43727. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43728. */
  43729. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43730. this.source = source;
  43731. this.pointerX = pointerX;
  43732. this.pointerY = pointerY;
  43733. this.meshUnderPointer = meshUnderPointer;
  43734. this.sourceEvent = sourceEvent;
  43735. this.additionalData = additionalData;
  43736. }
  43737. /**
  43738. * Helper function to auto-create an ActionEvent from a source mesh.
  43739. * @param source The source mesh that triggered the event
  43740. * @param evt {Event} The original (browser) event
  43741. */
  43742. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43743. var scene = source.getScene();
  43744. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43745. };
  43746. /**
  43747. * Helper function to auto-create an ActionEvent from a source mesh.
  43748. * @param source The source sprite that triggered the event
  43749. * @param scene Scene associated with the sprite
  43750. * @param evt {Event} The original (browser) event
  43751. */
  43752. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43753. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43754. };
  43755. /**
  43756. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43757. * @param scene the scene where the event occurred
  43758. * @param evt {Event} The original (browser) event
  43759. */
  43760. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43761. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43762. };
  43763. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43764. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43765. };
  43766. return ActionEvent;
  43767. }());
  43768. BABYLON.ActionEvent = ActionEvent;
  43769. /**
  43770. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43771. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43772. */
  43773. var ActionManager = /** @class */ (function () {
  43774. function ActionManager(scene) {
  43775. // Members
  43776. this.actions = new Array();
  43777. this.hoverCursor = '';
  43778. this._scene = scene;
  43779. scene._actionManagers.push(this);
  43780. }
  43781. Object.defineProperty(ActionManager, "NothingTrigger", {
  43782. get: function () {
  43783. return ActionManager._NothingTrigger;
  43784. },
  43785. enumerable: true,
  43786. configurable: true
  43787. });
  43788. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43789. get: function () {
  43790. return ActionManager._OnPickTrigger;
  43791. },
  43792. enumerable: true,
  43793. configurable: true
  43794. });
  43795. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43796. get: function () {
  43797. return ActionManager._OnLeftPickTrigger;
  43798. },
  43799. enumerable: true,
  43800. configurable: true
  43801. });
  43802. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43803. get: function () {
  43804. return ActionManager._OnRightPickTrigger;
  43805. },
  43806. enumerable: true,
  43807. configurable: true
  43808. });
  43809. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43810. get: function () {
  43811. return ActionManager._OnCenterPickTrigger;
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43817. get: function () {
  43818. return ActionManager._OnPickDownTrigger;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43824. get: function () {
  43825. return ActionManager._OnDoublePickTrigger;
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43831. get: function () {
  43832. return ActionManager._OnPickUpTrigger;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43838. /// This trigger will only be raised if you also declared a OnPickDown
  43839. get: function () {
  43840. return ActionManager._OnPickOutTrigger;
  43841. },
  43842. enumerable: true,
  43843. configurable: true
  43844. });
  43845. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43846. get: function () {
  43847. return ActionManager._OnLongPressTrigger;
  43848. },
  43849. enumerable: true,
  43850. configurable: true
  43851. });
  43852. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43853. get: function () {
  43854. return ActionManager._OnPointerOverTrigger;
  43855. },
  43856. enumerable: true,
  43857. configurable: true
  43858. });
  43859. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43860. get: function () {
  43861. return ActionManager._OnPointerOutTrigger;
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43867. get: function () {
  43868. return ActionManager._OnEveryFrameTrigger;
  43869. },
  43870. enumerable: true,
  43871. configurable: true
  43872. });
  43873. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43874. get: function () {
  43875. return ActionManager._OnIntersectionEnterTrigger;
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43881. get: function () {
  43882. return ActionManager._OnIntersectionExitTrigger;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43888. get: function () {
  43889. return ActionManager._OnKeyDownTrigger;
  43890. },
  43891. enumerable: true,
  43892. configurable: true
  43893. });
  43894. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43895. get: function () {
  43896. return ActionManager._OnKeyUpTrigger;
  43897. },
  43898. enumerable: true,
  43899. configurable: true
  43900. });
  43901. // Methods
  43902. ActionManager.prototype.dispose = function () {
  43903. var index = this._scene._actionManagers.indexOf(this);
  43904. for (var i = 0; i < this.actions.length; i++) {
  43905. var action = this.actions[i];
  43906. ActionManager.Triggers[action.trigger]--;
  43907. if (ActionManager.Triggers[action.trigger] === 0) {
  43908. delete ActionManager.Triggers[action.trigger];
  43909. }
  43910. }
  43911. if (index > -1) {
  43912. this._scene._actionManagers.splice(index, 1);
  43913. }
  43914. };
  43915. ActionManager.prototype.getScene = function () {
  43916. return this._scene;
  43917. };
  43918. /**
  43919. * Does this action manager handles actions of any of the given triggers
  43920. * @param {number[]} triggers - the triggers to be tested
  43921. * @return {boolean} whether one (or more) of the triggers is handeled
  43922. */
  43923. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43924. for (var index = 0; index < this.actions.length; index++) {
  43925. var action = this.actions[index];
  43926. if (triggers.indexOf(action.trigger) > -1) {
  43927. return true;
  43928. }
  43929. }
  43930. return false;
  43931. };
  43932. /**
  43933. * Does this action manager handles actions of a given trigger
  43934. * @param {number} trigger - the trigger to be tested
  43935. * @return {boolean} whether the trigger is handeled
  43936. */
  43937. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43938. for (var index = 0; index < this.actions.length; index++) {
  43939. var action = this.actions[index];
  43940. if (action.trigger === trigger) {
  43941. return true;
  43942. }
  43943. }
  43944. return false;
  43945. };
  43946. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43947. /**
  43948. * Does this action manager has pointer triggers
  43949. * @return {boolean} whether or not it has pointer triggers
  43950. */
  43951. get: function () {
  43952. for (var index = 0; index < this.actions.length; index++) {
  43953. var action = this.actions[index];
  43954. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43955. return true;
  43956. }
  43957. }
  43958. return false;
  43959. },
  43960. enumerable: true,
  43961. configurable: true
  43962. });
  43963. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43964. /**
  43965. * Does this action manager has pick triggers
  43966. * @return {boolean} whether or not it has pick triggers
  43967. */
  43968. get: function () {
  43969. for (var index = 0; index < this.actions.length; index++) {
  43970. var action = this.actions[index];
  43971. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43972. return true;
  43973. }
  43974. }
  43975. return false;
  43976. },
  43977. enumerable: true,
  43978. configurable: true
  43979. });
  43980. Object.defineProperty(ActionManager, "HasTriggers", {
  43981. /**
  43982. * Does exist one action manager with at least one trigger
  43983. * @return {boolean} whether or not it exists one action manager with one trigger
  43984. **/
  43985. get: function () {
  43986. for (var t in ActionManager.Triggers) {
  43987. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43988. return true;
  43989. }
  43990. }
  43991. return false;
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43997. /**
  43998. * Does exist one action manager with at least one pick trigger
  43999. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44000. **/
  44001. get: function () {
  44002. for (var t in ActionManager.Triggers) {
  44003. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44004. var t_int = parseInt(t);
  44005. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44006. return true;
  44007. }
  44008. }
  44009. }
  44010. return false;
  44011. },
  44012. enumerable: true,
  44013. configurable: true
  44014. });
  44015. /**
  44016. * Does exist one action manager that handles actions of a given trigger
  44017. * @param {number} trigger - the trigger to be tested
  44018. * @return {boolean} whether the trigger is handeled by at least one action manager
  44019. **/
  44020. ActionManager.HasSpecificTrigger = function (trigger) {
  44021. for (var t in ActionManager.Triggers) {
  44022. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44023. var t_int = parseInt(t);
  44024. if (t_int === trigger) {
  44025. return true;
  44026. }
  44027. }
  44028. }
  44029. return false;
  44030. };
  44031. /**
  44032. * Registers an action to this action manager
  44033. * @param {BABYLON.Action} action - the action to be registered
  44034. * @return {BABYLON.Action} the action amended (prepared) after registration
  44035. */
  44036. ActionManager.prototype.registerAction = function (action) {
  44037. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44038. if (this.getScene().actionManager !== this) {
  44039. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44040. return null;
  44041. }
  44042. }
  44043. this.actions.push(action);
  44044. if (ActionManager.Triggers[action.trigger]) {
  44045. ActionManager.Triggers[action.trigger]++;
  44046. }
  44047. else {
  44048. ActionManager.Triggers[action.trigger] = 1;
  44049. }
  44050. action._actionManager = this;
  44051. action._prepare();
  44052. return action;
  44053. };
  44054. /**
  44055. * Process a specific trigger
  44056. * @param {number} trigger - the trigger to process
  44057. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44058. */
  44059. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44060. for (var index = 0; index < this.actions.length; index++) {
  44061. var action = this.actions[index];
  44062. if (action.trigger === trigger) {
  44063. if (evt) {
  44064. if (trigger === ActionManager.OnKeyUpTrigger
  44065. || trigger === ActionManager.OnKeyDownTrigger) {
  44066. var parameter = action.getTriggerParameter();
  44067. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44068. if (!parameter.toLowerCase) {
  44069. continue;
  44070. }
  44071. var lowerCase = parameter.toLowerCase();
  44072. if (lowerCase !== evt.sourceEvent.key) {
  44073. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44074. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44075. if (actualkey !== lowerCase) {
  44076. continue;
  44077. }
  44078. }
  44079. }
  44080. }
  44081. }
  44082. action._executeCurrent(evt);
  44083. }
  44084. }
  44085. };
  44086. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44087. var properties = propertyPath.split(".");
  44088. for (var index = 0; index < properties.length - 1; index++) {
  44089. target = target[properties[index]];
  44090. }
  44091. return target;
  44092. };
  44093. ActionManager.prototype._getProperty = function (propertyPath) {
  44094. var properties = propertyPath.split(".");
  44095. return properties[properties.length - 1];
  44096. };
  44097. ActionManager.prototype.serialize = function (name) {
  44098. var root = {
  44099. children: new Array(),
  44100. name: name,
  44101. type: 3,
  44102. properties: new Array() // Empty for root but required
  44103. };
  44104. for (var i = 0; i < this.actions.length; i++) {
  44105. var triggerObject = {
  44106. type: 0,
  44107. children: new Array(),
  44108. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44109. properties: new Array()
  44110. };
  44111. var triggerOptions = this.actions[i].triggerOptions;
  44112. if (triggerOptions && typeof triggerOptions !== "number") {
  44113. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44114. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44115. }
  44116. else {
  44117. var parameter = {};
  44118. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44119. if (triggerOptions.parameter.mesh) {
  44120. parameter._meshId = triggerOptions.parameter.mesh.id;
  44121. }
  44122. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44123. }
  44124. }
  44125. // Serialize child action, recursively
  44126. this.actions[i].serialize(triggerObject);
  44127. // Add serialized trigger
  44128. root.children.push(triggerObject);
  44129. }
  44130. return root;
  44131. };
  44132. ActionManager.Parse = function (parsedActions, object, scene) {
  44133. var actionManager = new ActionManager(scene);
  44134. if (object === null)
  44135. scene.actionManager = actionManager;
  44136. else
  44137. object.actionManager = actionManager;
  44138. // instanciate a new object
  44139. var instanciate = function (name, params) {
  44140. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44141. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44142. newInstance.constructor.apply(newInstance, params);
  44143. return newInstance;
  44144. };
  44145. var parseParameter = function (name, value, target, propertyPath) {
  44146. if (propertyPath === null) {
  44147. // String, boolean or float
  44148. var floatValue = parseFloat(value);
  44149. if (value === "true" || value === "false")
  44150. return value === "true";
  44151. else
  44152. return isNaN(floatValue) ? value : floatValue;
  44153. }
  44154. var effectiveTarget = propertyPath.split(".");
  44155. var values = value.split(",");
  44156. // Get effective Target
  44157. for (var i = 0; i < effectiveTarget.length; i++) {
  44158. target = target[effectiveTarget[i]];
  44159. }
  44160. // Return appropriate value with its type
  44161. if (typeof (target) === "boolean")
  44162. return values[0] === "true";
  44163. if (typeof (target) === "string")
  44164. return values[0];
  44165. // Parameters with multiple values such as Vector3 etc.
  44166. var split = new Array();
  44167. for (var i = 0; i < values.length; i++)
  44168. split.push(parseFloat(values[i]));
  44169. if (target instanceof BABYLON.Vector3)
  44170. return BABYLON.Vector3.FromArray(split);
  44171. if (target instanceof BABYLON.Vector4)
  44172. return BABYLON.Vector4.FromArray(split);
  44173. if (target instanceof BABYLON.Color3)
  44174. return BABYLON.Color3.FromArray(split);
  44175. if (target instanceof BABYLON.Color4)
  44176. return BABYLON.Color4.FromArray(split);
  44177. return parseFloat(values[0]);
  44178. };
  44179. // traverse graph per trigger
  44180. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44181. if (combineArray === void 0) { combineArray = null; }
  44182. if (parsedAction.detached)
  44183. return;
  44184. var parameters = new Array();
  44185. var target = null;
  44186. var propertyPath = null;
  44187. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44188. // Parameters
  44189. if (parsedAction.type === 2)
  44190. parameters.push(actionManager);
  44191. else
  44192. parameters.push(trigger);
  44193. if (combine) {
  44194. var actions = new Array();
  44195. for (var j = 0; j < parsedAction.combine.length; j++) {
  44196. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44197. }
  44198. parameters.push(actions);
  44199. }
  44200. else {
  44201. for (var i = 0; i < parsedAction.properties.length; i++) {
  44202. var value = parsedAction.properties[i].value;
  44203. var name = parsedAction.properties[i].name;
  44204. var targetType = parsedAction.properties[i].targetType;
  44205. if (name === "target")
  44206. if (targetType !== null && targetType === "SceneProperties")
  44207. value = target = scene;
  44208. else
  44209. value = target = scene.getNodeByName(value);
  44210. else if (name === "parent")
  44211. value = scene.getNodeByName(value);
  44212. else if (name === "sound")
  44213. value = scene.getSoundByName(value);
  44214. else if (name !== "propertyPath") {
  44215. if (parsedAction.type === 2 && name === "operator")
  44216. value = BABYLON.ValueCondition[value];
  44217. else
  44218. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44219. }
  44220. else {
  44221. propertyPath = value;
  44222. }
  44223. parameters.push(value);
  44224. }
  44225. }
  44226. if (combineArray === null) {
  44227. parameters.push(condition);
  44228. }
  44229. else {
  44230. parameters.push(null);
  44231. }
  44232. // If interpolate value action
  44233. if (parsedAction.name === "InterpolateValueAction") {
  44234. var param = parameters[parameters.length - 2];
  44235. parameters[parameters.length - 1] = param;
  44236. parameters[parameters.length - 2] = condition;
  44237. }
  44238. // Action or condition(s) and not CombineAction
  44239. var newAction = instanciate(parsedAction.name, parameters);
  44240. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44241. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44242. if (action)
  44243. action.then(nothing);
  44244. else
  44245. actionManager.registerAction(nothing);
  44246. action = nothing;
  44247. }
  44248. if (combineArray === null) {
  44249. if (newAction instanceof BABYLON.Condition) {
  44250. condition = newAction;
  44251. newAction = action;
  44252. }
  44253. else {
  44254. condition = null;
  44255. if (action)
  44256. action.then(newAction);
  44257. else
  44258. actionManager.registerAction(newAction);
  44259. }
  44260. }
  44261. else {
  44262. combineArray.push(newAction);
  44263. }
  44264. for (var i = 0; i < parsedAction.children.length; i++)
  44265. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44266. };
  44267. // triggers
  44268. for (var i = 0; i < parsedActions.children.length; i++) {
  44269. var triggerParams;
  44270. var trigger = parsedActions.children[i];
  44271. if (trigger.properties.length > 0) {
  44272. var param = trigger.properties[0].value;
  44273. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44274. if (value._meshId) {
  44275. value.mesh = scene.getMeshByID(value._meshId);
  44276. }
  44277. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44278. }
  44279. else
  44280. triggerParams = ActionManager[trigger.name];
  44281. for (var j = 0; j < trigger.children.length; j++) {
  44282. if (!trigger.detached)
  44283. traverse(trigger.children[j], triggerParams, null, null);
  44284. }
  44285. }
  44286. };
  44287. ActionManager.GetTriggerName = function (trigger) {
  44288. switch (trigger) {
  44289. case 0: return "NothingTrigger";
  44290. case 1: return "OnPickTrigger";
  44291. case 2: return "OnLeftPickTrigger";
  44292. case 3: return "OnRightPickTrigger";
  44293. case 4: return "OnCenterPickTrigger";
  44294. case 5: return "OnPickDownTrigger";
  44295. case 6: return "OnPickUpTrigger";
  44296. case 7: return "OnLongPressTrigger";
  44297. case 8: return "OnPointerOverTrigger";
  44298. case 9: return "OnPointerOutTrigger";
  44299. case 10: return "OnEveryFrameTrigger";
  44300. case 11: return "OnIntersectionEnterTrigger";
  44301. case 12: return "OnIntersectionExitTrigger";
  44302. case 13: return "OnKeyDownTrigger";
  44303. case 14: return "OnKeyUpTrigger";
  44304. case 15: return "OnPickOutTrigger";
  44305. default: return "";
  44306. }
  44307. };
  44308. // Statics
  44309. ActionManager._NothingTrigger = 0;
  44310. ActionManager._OnPickTrigger = 1;
  44311. ActionManager._OnLeftPickTrigger = 2;
  44312. ActionManager._OnRightPickTrigger = 3;
  44313. ActionManager._OnCenterPickTrigger = 4;
  44314. ActionManager._OnPickDownTrigger = 5;
  44315. ActionManager._OnDoublePickTrigger = 6;
  44316. ActionManager._OnPickUpTrigger = 7;
  44317. ActionManager._OnLongPressTrigger = 8;
  44318. ActionManager._OnPointerOverTrigger = 9;
  44319. ActionManager._OnPointerOutTrigger = 10;
  44320. ActionManager._OnEveryFrameTrigger = 11;
  44321. ActionManager._OnIntersectionEnterTrigger = 12;
  44322. ActionManager._OnIntersectionExitTrigger = 13;
  44323. ActionManager._OnKeyDownTrigger = 14;
  44324. ActionManager._OnKeyUpTrigger = 15;
  44325. ActionManager._OnPickOutTrigger = 16;
  44326. ActionManager.Triggers = {};
  44327. return ActionManager;
  44328. }());
  44329. BABYLON.ActionManager = ActionManager;
  44330. })(BABYLON || (BABYLON = {}));
  44331. //# sourceMappingURL=babylon.actionManager.js.map
  44332. var BABYLON;
  44333. (function (BABYLON) {
  44334. var InterpolateValueAction = /** @class */ (function (_super) {
  44335. __extends(InterpolateValueAction, _super);
  44336. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44337. if (duration === void 0) { duration = 1000; }
  44338. var _this = _super.call(this, triggerOptions, condition) || this;
  44339. _this.propertyPath = propertyPath;
  44340. _this.value = value;
  44341. _this.duration = duration;
  44342. _this.stopOtherAnimations = stopOtherAnimations;
  44343. _this.onInterpolationDone = onInterpolationDone;
  44344. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44345. _this._target = _this._effectiveTarget = target;
  44346. return _this;
  44347. }
  44348. InterpolateValueAction.prototype._prepare = function () {
  44349. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44350. this._property = this._getProperty(this.propertyPath);
  44351. };
  44352. InterpolateValueAction.prototype.execute = function () {
  44353. var _this = this;
  44354. var scene = this._actionManager.getScene();
  44355. var keys = [
  44356. {
  44357. frame: 0,
  44358. value: this._effectiveTarget[this._property]
  44359. }, {
  44360. frame: 100,
  44361. value: this.value
  44362. }
  44363. ];
  44364. var dataType;
  44365. if (typeof this.value === "number") {
  44366. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44367. }
  44368. else if (this.value instanceof BABYLON.Color3) {
  44369. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44370. }
  44371. else if (this.value instanceof BABYLON.Vector3) {
  44372. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44373. }
  44374. else if (this.value instanceof BABYLON.Matrix) {
  44375. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44376. }
  44377. else if (this.value instanceof BABYLON.Quaternion) {
  44378. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44379. }
  44380. else {
  44381. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44382. return;
  44383. }
  44384. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44385. animation.setKeys(keys);
  44386. if (this.stopOtherAnimations) {
  44387. scene.stopAnimation(this._effectiveTarget);
  44388. }
  44389. var wrapper = function () {
  44390. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44391. if (_this.onInterpolationDone) {
  44392. _this.onInterpolationDone();
  44393. }
  44394. };
  44395. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44396. };
  44397. InterpolateValueAction.prototype.serialize = function (parent) {
  44398. return _super.prototype._serialize.call(this, {
  44399. name: "InterpolateValueAction",
  44400. properties: [
  44401. BABYLON.Action._GetTargetProperty(this._target),
  44402. { name: "propertyPath", value: this.propertyPath },
  44403. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44404. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44405. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44406. ]
  44407. }, parent);
  44408. };
  44409. return InterpolateValueAction;
  44410. }(BABYLON.Action));
  44411. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44412. })(BABYLON || (BABYLON = {}));
  44413. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44414. var BABYLON;
  44415. (function (BABYLON) {
  44416. var SwitchBooleanAction = /** @class */ (function (_super) {
  44417. __extends(SwitchBooleanAction, _super);
  44418. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44419. var _this = _super.call(this, triggerOptions, condition) || this;
  44420. _this.propertyPath = propertyPath;
  44421. _this._target = _this._effectiveTarget = target;
  44422. return _this;
  44423. }
  44424. SwitchBooleanAction.prototype._prepare = function () {
  44425. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44426. this._property = this._getProperty(this.propertyPath);
  44427. };
  44428. SwitchBooleanAction.prototype.execute = function () {
  44429. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44430. };
  44431. SwitchBooleanAction.prototype.serialize = function (parent) {
  44432. return _super.prototype._serialize.call(this, {
  44433. name: "SwitchBooleanAction",
  44434. properties: [
  44435. BABYLON.Action._GetTargetProperty(this._target),
  44436. { name: "propertyPath", value: this.propertyPath }
  44437. ]
  44438. }, parent);
  44439. };
  44440. return SwitchBooleanAction;
  44441. }(BABYLON.Action));
  44442. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44443. var SetStateAction = /** @class */ (function (_super) {
  44444. __extends(SetStateAction, _super);
  44445. function SetStateAction(triggerOptions, target, value, condition) {
  44446. var _this = _super.call(this, triggerOptions, condition) || this;
  44447. _this.value = value;
  44448. _this._target = target;
  44449. return _this;
  44450. }
  44451. SetStateAction.prototype.execute = function () {
  44452. this._target.state = this.value;
  44453. };
  44454. SetStateAction.prototype.serialize = function (parent) {
  44455. return _super.prototype._serialize.call(this, {
  44456. name: "SetStateAction",
  44457. properties: [
  44458. BABYLON.Action._GetTargetProperty(this._target),
  44459. { name: "value", value: this.value }
  44460. ]
  44461. }, parent);
  44462. };
  44463. return SetStateAction;
  44464. }(BABYLON.Action));
  44465. BABYLON.SetStateAction = SetStateAction;
  44466. var SetValueAction = /** @class */ (function (_super) {
  44467. __extends(SetValueAction, _super);
  44468. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44469. var _this = _super.call(this, triggerOptions, condition) || this;
  44470. _this.propertyPath = propertyPath;
  44471. _this.value = value;
  44472. _this._target = _this._effectiveTarget = target;
  44473. return _this;
  44474. }
  44475. SetValueAction.prototype._prepare = function () {
  44476. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44477. this._property = this._getProperty(this.propertyPath);
  44478. };
  44479. SetValueAction.prototype.execute = function () {
  44480. this._effectiveTarget[this._property] = this.value;
  44481. if (this._target.markAsDirty) {
  44482. this._target.markAsDirty(this._property);
  44483. }
  44484. };
  44485. SetValueAction.prototype.serialize = function (parent) {
  44486. return _super.prototype._serialize.call(this, {
  44487. name: "SetValueAction",
  44488. properties: [
  44489. BABYLON.Action._GetTargetProperty(this._target),
  44490. { name: "propertyPath", value: this.propertyPath },
  44491. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44492. ]
  44493. }, parent);
  44494. };
  44495. return SetValueAction;
  44496. }(BABYLON.Action));
  44497. BABYLON.SetValueAction = SetValueAction;
  44498. var IncrementValueAction = /** @class */ (function (_super) {
  44499. __extends(IncrementValueAction, _super);
  44500. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44501. var _this = _super.call(this, triggerOptions, condition) || this;
  44502. _this.propertyPath = propertyPath;
  44503. _this.value = value;
  44504. _this._target = _this._effectiveTarget = target;
  44505. return _this;
  44506. }
  44507. IncrementValueAction.prototype._prepare = function () {
  44508. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44509. this._property = this._getProperty(this.propertyPath);
  44510. if (typeof this._effectiveTarget[this._property] !== "number") {
  44511. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44512. }
  44513. };
  44514. IncrementValueAction.prototype.execute = function () {
  44515. this._effectiveTarget[this._property] += this.value;
  44516. if (this._target.markAsDirty) {
  44517. this._target.markAsDirty(this._property);
  44518. }
  44519. };
  44520. IncrementValueAction.prototype.serialize = function (parent) {
  44521. return _super.prototype._serialize.call(this, {
  44522. name: "IncrementValueAction",
  44523. properties: [
  44524. BABYLON.Action._GetTargetProperty(this._target),
  44525. { name: "propertyPath", value: this.propertyPath },
  44526. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44527. ]
  44528. }, parent);
  44529. };
  44530. return IncrementValueAction;
  44531. }(BABYLON.Action));
  44532. BABYLON.IncrementValueAction = IncrementValueAction;
  44533. var PlayAnimationAction = /** @class */ (function (_super) {
  44534. __extends(PlayAnimationAction, _super);
  44535. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44536. var _this = _super.call(this, triggerOptions, condition) || this;
  44537. _this.from = from;
  44538. _this.to = to;
  44539. _this.loop = loop;
  44540. _this._target = target;
  44541. return _this;
  44542. }
  44543. PlayAnimationAction.prototype._prepare = function () {
  44544. };
  44545. PlayAnimationAction.prototype.execute = function () {
  44546. var scene = this._actionManager.getScene();
  44547. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44548. };
  44549. PlayAnimationAction.prototype.serialize = function (parent) {
  44550. return _super.prototype._serialize.call(this, {
  44551. name: "PlayAnimationAction",
  44552. properties: [
  44553. BABYLON.Action._GetTargetProperty(this._target),
  44554. { name: "from", value: String(this.from) },
  44555. { name: "to", value: String(this.to) },
  44556. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44557. ]
  44558. }, parent);
  44559. };
  44560. return PlayAnimationAction;
  44561. }(BABYLON.Action));
  44562. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44563. var StopAnimationAction = /** @class */ (function (_super) {
  44564. __extends(StopAnimationAction, _super);
  44565. function StopAnimationAction(triggerOptions, target, condition) {
  44566. var _this = _super.call(this, triggerOptions, condition) || this;
  44567. _this._target = target;
  44568. return _this;
  44569. }
  44570. StopAnimationAction.prototype._prepare = function () {
  44571. };
  44572. StopAnimationAction.prototype.execute = function () {
  44573. var scene = this._actionManager.getScene();
  44574. scene.stopAnimation(this._target);
  44575. };
  44576. StopAnimationAction.prototype.serialize = function (parent) {
  44577. return _super.prototype._serialize.call(this, {
  44578. name: "StopAnimationAction",
  44579. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44580. }, parent);
  44581. };
  44582. return StopAnimationAction;
  44583. }(BABYLON.Action));
  44584. BABYLON.StopAnimationAction = StopAnimationAction;
  44585. var DoNothingAction = /** @class */ (function (_super) {
  44586. __extends(DoNothingAction, _super);
  44587. function DoNothingAction(triggerOptions, condition) {
  44588. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44589. return _super.call(this, triggerOptions, condition) || this;
  44590. }
  44591. DoNothingAction.prototype.execute = function () {
  44592. };
  44593. DoNothingAction.prototype.serialize = function (parent) {
  44594. return _super.prototype._serialize.call(this, {
  44595. name: "DoNothingAction",
  44596. properties: []
  44597. }, parent);
  44598. };
  44599. return DoNothingAction;
  44600. }(BABYLON.Action));
  44601. BABYLON.DoNothingAction = DoNothingAction;
  44602. var CombineAction = /** @class */ (function (_super) {
  44603. __extends(CombineAction, _super);
  44604. function CombineAction(triggerOptions, children, condition) {
  44605. var _this = _super.call(this, triggerOptions, condition) || this;
  44606. _this.children = children;
  44607. return _this;
  44608. }
  44609. CombineAction.prototype._prepare = function () {
  44610. for (var index = 0; index < this.children.length; index++) {
  44611. this.children[index]._actionManager = this._actionManager;
  44612. this.children[index]._prepare();
  44613. }
  44614. };
  44615. CombineAction.prototype.execute = function (evt) {
  44616. for (var index = 0; index < this.children.length; index++) {
  44617. this.children[index].execute(evt);
  44618. }
  44619. };
  44620. CombineAction.prototype.serialize = function (parent) {
  44621. var serializationObject = _super.prototype._serialize.call(this, {
  44622. name: "CombineAction",
  44623. properties: [],
  44624. combine: []
  44625. }, parent);
  44626. for (var i = 0; i < this.children.length; i++) {
  44627. serializationObject.combine.push(this.children[i].serialize(null));
  44628. }
  44629. return serializationObject;
  44630. };
  44631. return CombineAction;
  44632. }(BABYLON.Action));
  44633. BABYLON.CombineAction = CombineAction;
  44634. var ExecuteCodeAction = /** @class */ (function (_super) {
  44635. __extends(ExecuteCodeAction, _super);
  44636. function ExecuteCodeAction(triggerOptions, func, condition) {
  44637. var _this = _super.call(this, triggerOptions, condition) || this;
  44638. _this.func = func;
  44639. return _this;
  44640. }
  44641. ExecuteCodeAction.prototype.execute = function (evt) {
  44642. this.func(evt);
  44643. };
  44644. return ExecuteCodeAction;
  44645. }(BABYLON.Action));
  44646. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44647. var SetParentAction = /** @class */ (function (_super) {
  44648. __extends(SetParentAction, _super);
  44649. function SetParentAction(triggerOptions, target, parent, condition) {
  44650. var _this = _super.call(this, triggerOptions, condition) || this;
  44651. _this._target = target;
  44652. _this._parent = parent;
  44653. return _this;
  44654. }
  44655. SetParentAction.prototype._prepare = function () {
  44656. };
  44657. SetParentAction.prototype.execute = function () {
  44658. if (this._target.parent === this._parent) {
  44659. return;
  44660. }
  44661. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44662. invertParentWorldMatrix.invert();
  44663. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44664. this._target.parent = this._parent;
  44665. };
  44666. SetParentAction.prototype.serialize = function (parent) {
  44667. return _super.prototype._serialize.call(this, {
  44668. name: "SetParentAction",
  44669. properties: [
  44670. BABYLON.Action._GetTargetProperty(this._target),
  44671. BABYLON.Action._GetTargetProperty(this._parent),
  44672. ]
  44673. }, parent);
  44674. };
  44675. return SetParentAction;
  44676. }(BABYLON.Action));
  44677. BABYLON.SetParentAction = SetParentAction;
  44678. var PlaySoundAction = /** @class */ (function (_super) {
  44679. __extends(PlaySoundAction, _super);
  44680. function PlaySoundAction(triggerOptions, sound, condition) {
  44681. var _this = _super.call(this, triggerOptions, condition) || this;
  44682. _this._sound = sound;
  44683. return _this;
  44684. }
  44685. PlaySoundAction.prototype._prepare = function () {
  44686. };
  44687. PlaySoundAction.prototype.execute = function () {
  44688. if (this._sound !== undefined)
  44689. this._sound.play();
  44690. };
  44691. PlaySoundAction.prototype.serialize = function (parent) {
  44692. return _super.prototype._serialize.call(this, {
  44693. name: "PlaySoundAction",
  44694. properties: [{ name: "sound", value: this._sound.name }]
  44695. }, parent);
  44696. };
  44697. return PlaySoundAction;
  44698. }(BABYLON.Action));
  44699. BABYLON.PlaySoundAction = PlaySoundAction;
  44700. var StopSoundAction = /** @class */ (function (_super) {
  44701. __extends(StopSoundAction, _super);
  44702. function StopSoundAction(triggerOptions, sound, condition) {
  44703. var _this = _super.call(this, triggerOptions, condition) || this;
  44704. _this._sound = sound;
  44705. return _this;
  44706. }
  44707. StopSoundAction.prototype._prepare = function () {
  44708. };
  44709. StopSoundAction.prototype.execute = function () {
  44710. if (this._sound !== undefined)
  44711. this._sound.stop();
  44712. };
  44713. StopSoundAction.prototype.serialize = function (parent) {
  44714. return _super.prototype._serialize.call(this, {
  44715. name: "StopSoundAction",
  44716. properties: [{ name: "sound", value: this._sound.name }]
  44717. }, parent);
  44718. };
  44719. return StopSoundAction;
  44720. }(BABYLON.Action));
  44721. BABYLON.StopSoundAction = StopSoundAction;
  44722. })(BABYLON || (BABYLON = {}));
  44723. //# sourceMappingURL=babylon.directActions.js.map
  44724. var BABYLON;
  44725. (function (BABYLON) {
  44726. var SpriteManager = /** @class */ (function () {
  44727. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44728. if (epsilon === void 0) { epsilon = 0.01; }
  44729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44730. this.name = name;
  44731. this.sprites = new Array();
  44732. this.renderingGroupId = 0;
  44733. this.layerMask = 0x0FFFFFFF;
  44734. this.fogEnabled = true;
  44735. this.isPickable = false;
  44736. /**
  44737. * An event triggered when the manager is disposed.
  44738. * @type {BABYLON.Observable}
  44739. */
  44740. this.onDisposeObservable = new BABYLON.Observable();
  44741. this._vertexBuffers = {};
  44742. this._capacity = capacity;
  44743. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44744. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44745. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44746. if (cellSize.width && cellSize.height) {
  44747. this.cellWidth = cellSize.width;
  44748. this.cellHeight = cellSize.height;
  44749. }
  44750. else if (cellSize !== undefined) {
  44751. this.cellWidth = cellSize;
  44752. this.cellHeight = cellSize;
  44753. }
  44754. else {
  44755. return;
  44756. }
  44757. this._epsilon = epsilon;
  44758. this._scene = scene;
  44759. this._scene.spriteManagers.push(this);
  44760. var indices = [];
  44761. var index = 0;
  44762. for (var count = 0; count < capacity; count++) {
  44763. indices.push(index);
  44764. indices.push(index + 1);
  44765. indices.push(index + 2);
  44766. indices.push(index);
  44767. indices.push(index + 2);
  44768. indices.push(index + 3);
  44769. index += 4;
  44770. }
  44771. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44772. // VBO
  44773. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44774. this._vertexData = new Float32Array(capacity * 16 * 4);
  44775. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44776. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44777. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44778. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44779. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44781. this._vertexBuffers["options"] = options;
  44782. this._vertexBuffers["cellInfo"] = cellInfo;
  44783. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44784. // Effects
  44785. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44786. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44787. }
  44788. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44789. set: function (callback) {
  44790. if (this._onDisposeObserver) {
  44791. this.onDisposeObservable.remove(this._onDisposeObserver);
  44792. }
  44793. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44794. },
  44795. enumerable: true,
  44796. configurable: true
  44797. });
  44798. Object.defineProperty(SpriteManager.prototype, "texture", {
  44799. get: function () {
  44800. return this._spriteTexture;
  44801. },
  44802. set: function (value) {
  44803. this._spriteTexture = value;
  44804. },
  44805. enumerable: true,
  44806. configurable: true
  44807. });
  44808. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44809. var arrayOffset = index * 16;
  44810. if (offsetX === 0)
  44811. offsetX = this._epsilon;
  44812. else if (offsetX === 1)
  44813. offsetX = 1 - this._epsilon;
  44814. if (offsetY === 0)
  44815. offsetY = this._epsilon;
  44816. else if (offsetY === 1)
  44817. offsetY = 1 - this._epsilon;
  44818. this._vertexData[arrayOffset] = sprite.position.x;
  44819. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44820. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44821. this._vertexData[arrayOffset + 3] = sprite.angle;
  44822. this._vertexData[arrayOffset + 4] = sprite.width;
  44823. this._vertexData[arrayOffset + 5] = sprite.height;
  44824. this._vertexData[arrayOffset + 6] = offsetX;
  44825. this._vertexData[arrayOffset + 7] = offsetY;
  44826. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44827. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44828. var offset = (sprite.cellIndex / rowSize) >> 0;
  44829. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44830. this._vertexData[arrayOffset + 11] = offset;
  44831. // Color
  44832. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44833. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44834. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44835. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44836. };
  44837. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44838. var count = Math.min(this._capacity, this.sprites.length);
  44839. var min = BABYLON.Vector3.Zero();
  44840. var max = BABYLON.Vector3.Zero();
  44841. var distance = Number.MAX_VALUE;
  44842. var currentSprite = null;
  44843. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44844. var cameraView = camera.getViewMatrix();
  44845. for (var index = 0; index < count; index++) {
  44846. var sprite = this.sprites[index];
  44847. if (!sprite) {
  44848. continue;
  44849. }
  44850. if (predicate) {
  44851. if (!predicate(sprite)) {
  44852. continue;
  44853. }
  44854. }
  44855. else if (!sprite.isPickable) {
  44856. continue;
  44857. }
  44858. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44859. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44860. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44861. if (ray.intersectsBoxMinMax(min, max)) {
  44862. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44863. if (distance > currentDistance) {
  44864. distance = currentDistance;
  44865. currentSprite = sprite;
  44866. if (fastCheck) {
  44867. break;
  44868. }
  44869. }
  44870. }
  44871. }
  44872. if (currentSprite) {
  44873. var result = new BABYLON.PickingInfo();
  44874. result.hit = true;
  44875. result.pickedSprite = currentSprite;
  44876. result.distance = distance;
  44877. return result;
  44878. }
  44879. return null;
  44880. };
  44881. SpriteManager.prototype.render = function () {
  44882. // Check
  44883. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44884. return;
  44885. var engine = this._scene.getEngine();
  44886. var baseSize = this._spriteTexture.getBaseSize();
  44887. // Sprites
  44888. var deltaTime = engine.getDeltaTime();
  44889. var max = Math.min(this._capacity, this.sprites.length);
  44890. var rowSize = baseSize.width / this.cellWidth;
  44891. var offset = 0;
  44892. for (var index = 0; index < max; index++) {
  44893. var sprite = this.sprites[index];
  44894. if (!sprite) {
  44895. continue;
  44896. }
  44897. sprite._animate(deltaTime);
  44898. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44899. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44900. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44901. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44902. }
  44903. this._buffer.update(this._vertexData);
  44904. // Render
  44905. var effect = this._effectBase;
  44906. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44907. effect = this._effectFog;
  44908. }
  44909. engine.enableEffect(effect);
  44910. var viewMatrix = this._scene.getViewMatrix();
  44911. effect.setTexture("diffuseSampler", this._spriteTexture);
  44912. effect.setMatrix("view", viewMatrix);
  44913. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44914. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44915. // Fog
  44916. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44917. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44918. effect.setColor3("vFogColor", this._scene.fogColor);
  44919. }
  44920. // VBOs
  44921. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44922. // Draw order
  44923. engine.setDepthFunctionToLessOrEqual();
  44924. effect.setBool("alphaTest", true);
  44925. engine.setColorWrite(false);
  44926. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44927. engine.setColorWrite(true);
  44928. effect.setBool("alphaTest", false);
  44929. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44931. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44932. };
  44933. SpriteManager.prototype.dispose = function () {
  44934. if (this._buffer) {
  44935. this._buffer.dispose();
  44936. this._buffer = null;
  44937. }
  44938. if (this._indexBuffer) {
  44939. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44940. this._indexBuffer = null;
  44941. }
  44942. if (this._spriteTexture) {
  44943. this._spriteTexture.dispose();
  44944. this._spriteTexture = null;
  44945. }
  44946. // Remove from scene
  44947. var index = this._scene.spriteManagers.indexOf(this);
  44948. this._scene.spriteManagers.splice(index, 1);
  44949. // Callback
  44950. this.onDisposeObservable.notifyObservers(this);
  44951. this.onDisposeObservable.clear();
  44952. };
  44953. return SpriteManager;
  44954. }());
  44955. BABYLON.SpriteManager = SpriteManager;
  44956. })(BABYLON || (BABYLON = {}));
  44957. //# sourceMappingURL=babylon.spriteManager.js.map
  44958. var BABYLON;
  44959. (function (BABYLON) {
  44960. var Sprite = /** @class */ (function () {
  44961. function Sprite(name, manager) {
  44962. this.name = name;
  44963. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44964. this.width = 1.0;
  44965. this.height = 1.0;
  44966. this.angle = 0;
  44967. this.cellIndex = 0;
  44968. this.invertU = 0;
  44969. this.invertV = 0;
  44970. this.animations = new Array();
  44971. this.isPickable = false;
  44972. this._animationStarted = false;
  44973. this._loopAnimation = false;
  44974. this._fromIndex = 0;
  44975. this._toIndex = 0;
  44976. this._delay = 0;
  44977. this._direction = 1;
  44978. this._time = 0;
  44979. this._manager = manager;
  44980. this._manager.sprites.push(this);
  44981. this.position = BABYLON.Vector3.Zero();
  44982. }
  44983. Object.defineProperty(Sprite.prototype, "size", {
  44984. get: function () {
  44985. return this.width;
  44986. },
  44987. set: function (value) {
  44988. this.width = value;
  44989. this.height = value;
  44990. },
  44991. enumerable: true,
  44992. configurable: true
  44993. });
  44994. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44995. this._fromIndex = from;
  44996. this._toIndex = to;
  44997. this._loopAnimation = loop;
  44998. this._delay = delay;
  44999. this._animationStarted = true;
  45000. this._direction = from < to ? 1 : -1;
  45001. this.cellIndex = from;
  45002. this._time = 0;
  45003. this._onAnimationEnd = onAnimationEnd;
  45004. };
  45005. Sprite.prototype.stopAnimation = function () {
  45006. this._animationStarted = false;
  45007. };
  45008. Sprite.prototype._animate = function (deltaTime) {
  45009. if (!this._animationStarted)
  45010. return;
  45011. this._time += deltaTime;
  45012. if (this._time > this._delay) {
  45013. this._time = this._time % this._delay;
  45014. this.cellIndex += this._direction;
  45015. if (this.cellIndex > this._toIndex) {
  45016. if (this._loopAnimation) {
  45017. this.cellIndex = this._fromIndex;
  45018. }
  45019. else {
  45020. this.cellIndex = this._toIndex;
  45021. this._animationStarted = false;
  45022. if (this._onAnimationEnd) {
  45023. this._onAnimationEnd();
  45024. }
  45025. if (this.disposeWhenFinishedAnimating) {
  45026. this.dispose();
  45027. }
  45028. }
  45029. }
  45030. }
  45031. };
  45032. Sprite.prototype.dispose = function () {
  45033. for (var i = 0; i < this._manager.sprites.length; i++) {
  45034. if (this._manager.sprites[i] == this) {
  45035. this._manager.sprites.splice(i, 1);
  45036. }
  45037. }
  45038. };
  45039. return Sprite;
  45040. }());
  45041. BABYLON.Sprite = Sprite;
  45042. })(BABYLON || (BABYLON = {}));
  45043. //# sourceMappingURL=babylon.sprite.js.map
  45044. var BABYLON;
  45045. (function (BABYLON) {
  45046. var IntersectionInfo = /** @class */ (function () {
  45047. function IntersectionInfo(bu, bv, distance) {
  45048. this.bu = bu;
  45049. this.bv = bv;
  45050. this.distance = distance;
  45051. this.faceId = 0;
  45052. this.subMeshId = 0;
  45053. }
  45054. return IntersectionInfo;
  45055. }());
  45056. BABYLON.IntersectionInfo = IntersectionInfo;
  45057. var PickingInfo = /** @class */ (function () {
  45058. function PickingInfo() {
  45059. this.hit = false;
  45060. this.distance = 0;
  45061. this.pickedPoint = null;
  45062. this.pickedMesh = null;
  45063. this.bu = 0;
  45064. this.bv = 0;
  45065. this.faceId = -1;
  45066. this.subMeshId = 0;
  45067. this.pickedSprite = null;
  45068. }
  45069. // Methods
  45070. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45071. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45072. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45073. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45074. return null;
  45075. }
  45076. var indices = this.pickedMesh.getIndices();
  45077. if (!indices) {
  45078. return null;
  45079. }
  45080. var result;
  45081. if (useVerticesNormals) {
  45082. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45083. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45084. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45085. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45086. normal0 = normal0.scale(this.bu);
  45087. normal1 = normal1.scale(this.bv);
  45088. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45089. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45090. }
  45091. else {
  45092. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45093. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45094. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45095. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45096. var p1p2 = vertex1.subtract(vertex2);
  45097. var p3p2 = vertex3.subtract(vertex2);
  45098. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45099. }
  45100. if (useWorldCoordinates) {
  45101. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45102. }
  45103. return BABYLON.Vector3.Normalize(result);
  45104. };
  45105. PickingInfo.prototype.getTextureCoordinates = function () {
  45106. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45107. return null;
  45108. }
  45109. var indices = this.pickedMesh.getIndices();
  45110. if (!indices) {
  45111. return null;
  45112. }
  45113. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45114. if (!uvs) {
  45115. return null;
  45116. }
  45117. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45118. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45119. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45120. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45121. uv1 = uv1.scale(this.bu);
  45122. uv2 = uv2.scale(this.bv);
  45123. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45124. };
  45125. return PickingInfo;
  45126. }());
  45127. BABYLON.PickingInfo = PickingInfo;
  45128. })(BABYLON || (BABYLON = {}));
  45129. //# sourceMappingURL=babylon.pickingInfo.js.map
  45130. var BABYLON;
  45131. (function (BABYLON) {
  45132. var Ray = /** @class */ (function () {
  45133. function Ray(origin, direction, length) {
  45134. if (length === void 0) { length = Number.MAX_VALUE; }
  45135. this.origin = origin;
  45136. this.direction = direction;
  45137. this.length = length;
  45138. }
  45139. // Methods
  45140. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45141. var d = 0.0;
  45142. var maxValue = Number.MAX_VALUE;
  45143. var inv;
  45144. var min;
  45145. var max;
  45146. var temp;
  45147. if (Math.abs(this.direction.x) < 0.0000001) {
  45148. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45149. return false;
  45150. }
  45151. }
  45152. else {
  45153. inv = 1.0 / this.direction.x;
  45154. min = (minimum.x - this.origin.x) * inv;
  45155. max = (maximum.x - this.origin.x) * inv;
  45156. if (max === -Infinity) {
  45157. max = Infinity;
  45158. }
  45159. if (min > max) {
  45160. temp = min;
  45161. min = max;
  45162. max = temp;
  45163. }
  45164. d = Math.max(min, d);
  45165. maxValue = Math.min(max, maxValue);
  45166. if (d > maxValue) {
  45167. return false;
  45168. }
  45169. }
  45170. if (Math.abs(this.direction.y) < 0.0000001) {
  45171. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45172. return false;
  45173. }
  45174. }
  45175. else {
  45176. inv = 1.0 / this.direction.y;
  45177. min = (minimum.y - this.origin.y) * inv;
  45178. max = (maximum.y - this.origin.y) * inv;
  45179. if (max === -Infinity) {
  45180. max = Infinity;
  45181. }
  45182. if (min > max) {
  45183. temp = min;
  45184. min = max;
  45185. max = temp;
  45186. }
  45187. d = Math.max(min, d);
  45188. maxValue = Math.min(max, maxValue);
  45189. if (d > maxValue) {
  45190. return false;
  45191. }
  45192. }
  45193. if (Math.abs(this.direction.z) < 0.0000001) {
  45194. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45195. return false;
  45196. }
  45197. }
  45198. else {
  45199. inv = 1.0 / this.direction.z;
  45200. min = (minimum.z - this.origin.z) * inv;
  45201. max = (maximum.z - this.origin.z) * inv;
  45202. if (max === -Infinity) {
  45203. max = Infinity;
  45204. }
  45205. if (min > max) {
  45206. temp = min;
  45207. min = max;
  45208. max = temp;
  45209. }
  45210. d = Math.max(min, d);
  45211. maxValue = Math.min(max, maxValue);
  45212. if (d > maxValue) {
  45213. return false;
  45214. }
  45215. }
  45216. return true;
  45217. };
  45218. Ray.prototype.intersectsBox = function (box) {
  45219. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45220. };
  45221. Ray.prototype.intersectsSphere = function (sphere) {
  45222. var x = sphere.center.x - this.origin.x;
  45223. var y = sphere.center.y - this.origin.y;
  45224. var z = sphere.center.z - this.origin.z;
  45225. var pyth = (x * x) + (y * y) + (z * z);
  45226. var rr = sphere.radius * sphere.radius;
  45227. if (pyth <= rr) {
  45228. return true;
  45229. }
  45230. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45231. if (dot < 0.0) {
  45232. return false;
  45233. }
  45234. var temp = pyth - (dot * dot);
  45235. return temp <= rr;
  45236. };
  45237. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45238. if (!this._edge1) {
  45239. this._edge1 = BABYLON.Vector3.Zero();
  45240. this._edge2 = BABYLON.Vector3.Zero();
  45241. this._pvec = BABYLON.Vector3.Zero();
  45242. this._tvec = BABYLON.Vector3.Zero();
  45243. this._qvec = BABYLON.Vector3.Zero();
  45244. }
  45245. vertex1.subtractToRef(vertex0, this._edge1);
  45246. vertex2.subtractToRef(vertex0, this._edge2);
  45247. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45248. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45249. if (det === 0) {
  45250. return null;
  45251. }
  45252. var invdet = 1 / det;
  45253. this.origin.subtractToRef(vertex0, this._tvec);
  45254. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45255. if (bu < 0 || bu > 1.0) {
  45256. return null;
  45257. }
  45258. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45259. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45260. if (bv < 0 || bu + bv > 1.0) {
  45261. return null;
  45262. }
  45263. //check if the distance is longer than the predefined length.
  45264. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45265. if (distance > this.length) {
  45266. return null;
  45267. }
  45268. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45269. };
  45270. Ray.prototype.intersectsPlane = function (plane) {
  45271. var distance;
  45272. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45273. if (Math.abs(result1) < 9.99999997475243E-07) {
  45274. return null;
  45275. }
  45276. else {
  45277. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45278. distance = (-plane.d - result2) / result1;
  45279. if (distance < 0.0) {
  45280. if (distance < -9.99999997475243E-07) {
  45281. return null;
  45282. }
  45283. else {
  45284. return 0;
  45285. }
  45286. }
  45287. return distance;
  45288. }
  45289. };
  45290. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45291. var tm = BABYLON.Tmp.Matrix[0];
  45292. mesh.getWorldMatrix().invertToRef(tm);
  45293. if (this._tmpRay) {
  45294. Ray.TransformToRef(this, tm, this._tmpRay);
  45295. }
  45296. else {
  45297. this._tmpRay = Ray.Transform(this, tm);
  45298. }
  45299. return mesh.intersects(this._tmpRay, fastCheck);
  45300. };
  45301. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45302. if (results) {
  45303. results.length = 0;
  45304. }
  45305. else {
  45306. results = [];
  45307. }
  45308. for (var i = 0; i < meshes.length; i++) {
  45309. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45310. if (pickInfo.hit) {
  45311. results.push(pickInfo);
  45312. }
  45313. }
  45314. results.sort(this._comparePickingInfo);
  45315. return results;
  45316. };
  45317. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45318. if (pickingInfoA.distance < pickingInfoB.distance) {
  45319. return -1;
  45320. }
  45321. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45322. return 1;
  45323. }
  45324. else {
  45325. return 0;
  45326. }
  45327. };
  45328. /**
  45329. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45330. * @param sega the first point of the segment to test the intersection against
  45331. * @param segb the second point of the segment to test the intersection against
  45332. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45333. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45334. */
  45335. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45336. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45337. var u = segb.subtract(sega);
  45338. var v = rsegb.subtract(this.origin);
  45339. var w = sega.subtract(this.origin);
  45340. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45341. var b = BABYLON.Vector3.Dot(u, v);
  45342. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45343. var d = BABYLON.Vector3.Dot(u, w);
  45344. var e = BABYLON.Vector3.Dot(v, w);
  45345. var D = a * c - b * b; // always >= 0
  45346. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45347. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45348. // compute the line parameters of the two closest points
  45349. if (D < Ray.smallnum) {
  45350. sN = 0.0; // force using point P0 on segment S1
  45351. sD = 1.0; // to prevent possible division by 0.0 later
  45352. tN = e;
  45353. tD = c;
  45354. }
  45355. else {
  45356. sN = (b * e - c * d);
  45357. tN = (a * e - b * d);
  45358. if (sN < 0.0) {
  45359. sN = 0.0;
  45360. tN = e;
  45361. tD = c;
  45362. }
  45363. else if (sN > sD) {
  45364. sN = sD;
  45365. tN = e + b;
  45366. tD = c;
  45367. }
  45368. }
  45369. if (tN < 0.0) {
  45370. tN = 0.0;
  45371. // recompute sc for this edge
  45372. if (-d < 0.0) {
  45373. sN = 0.0;
  45374. }
  45375. else if (-d > a)
  45376. sN = sD;
  45377. else {
  45378. sN = -d;
  45379. sD = a;
  45380. }
  45381. }
  45382. else if (tN > tD) {
  45383. tN = tD;
  45384. // recompute sc for this edge
  45385. if ((-d + b) < 0.0) {
  45386. sN = 0;
  45387. }
  45388. else if ((-d + b) > a) {
  45389. sN = sD;
  45390. }
  45391. else {
  45392. sN = (-d + b);
  45393. sD = a;
  45394. }
  45395. }
  45396. // finally do the division to get sc and tc
  45397. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45398. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45399. // get the difference of the two closest points
  45400. var qtc = v.multiplyByFloats(tc, tc, tc);
  45401. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45402. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45403. if (isIntersected) {
  45404. return qtc.length();
  45405. }
  45406. return -1;
  45407. };
  45408. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45409. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45410. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45411. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45412. this.direction.normalize();
  45413. return this;
  45414. };
  45415. // Statics
  45416. Ray.Zero = function () {
  45417. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45418. };
  45419. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45420. var result = Ray.Zero();
  45421. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45422. };
  45423. /**
  45424. * 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
  45425. * transformed to the given world matrix.
  45426. * @param origin The origin point
  45427. * @param end The end point
  45428. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45429. */
  45430. Ray.CreateNewFromTo = function (origin, end, world) {
  45431. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45432. var direction = end.subtract(origin);
  45433. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45434. direction.normalize();
  45435. return Ray.Transform(new Ray(origin, direction, length), world);
  45436. };
  45437. Ray.Transform = function (ray, matrix) {
  45438. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45439. Ray.TransformToRef(ray, matrix, result);
  45440. return result;
  45441. };
  45442. Ray.TransformToRef = function (ray, matrix, result) {
  45443. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45444. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45445. result.length = ray.length;
  45446. var dir = result.direction;
  45447. var len = dir.length();
  45448. if (!(len === 0 || len === 1)) {
  45449. var num = 1.0 / len;
  45450. dir.x *= num;
  45451. dir.y *= num;
  45452. dir.z *= num;
  45453. result.length *= len;
  45454. }
  45455. };
  45456. Ray.smallnum = 0.00000001;
  45457. Ray.rayl = 10e8;
  45458. return Ray;
  45459. }());
  45460. BABYLON.Ray = Ray;
  45461. })(BABYLON || (BABYLON = {}));
  45462. //# sourceMappingURL=babylon.ray.js.map
  45463. var BABYLON;
  45464. (function (BABYLON) {
  45465. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45466. if (boxMin.x > sphereCenter.x + sphereRadius)
  45467. return false;
  45468. if (sphereCenter.x - sphereRadius > boxMax.x)
  45469. return false;
  45470. if (boxMin.y > sphereCenter.y + sphereRadius)
  45471. return false;
  45472. if (sphereCenter.y - sphereRadius > boxMax.y)
  45473. return false;
  45474. if (boxMin.z > sphereCenter.z + sphereRadius)
  45475. return false;
  45476. if (sphereCenter.z - sphereRadius > boxMax.z)
  45477. return false;
  45478. return true;
  45479. };
  45480. var getLowestRoot = (function () {
  45481. var result = { root: 0, found: false };
  45482. return function (a, b, c, maxR) {
  45483. result.root = 0;
  45484. result.found = false;
  45485. var determinant = b * b - 4.0 * a * c;
  45486. if (determinant < 0)
  45487. return result;
  45488. var sqrtD = Math.sqrt(determinant);
  45489. var r1 = (-b - sqrtD) / (2.0 * a);
  45490. var r2 = (-b + sqrtD) / (2.0 * a);
  45491. if (r1 > r2) {
  45492. var temp = r2;
  45493. r2 = r1;
  45494. r1 = temp;
  45495. }
  45496. if (r1 > 0 && r1 < maxR) {
  45497. result.root = r1;
  45498. result.found = true;
  45499. return result;
  45500. }
  45501. if (r2 > 0 && r2 < maxR) {
  45502. result.root = r2;
  45503. result.found = true;
  45504. return result;
  45505. }
  45506. return result;
  45507. };
  45508. })();
  45509. var Collider = /** @class */ (function () {
  45510. function Collider() {
  45511. this._collisionPoint = BABYLON.Vector3.Zero();
  45512. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45513. this._tempVector = BABYLON.Vector3.Zero();
  45514. this._tempVector2 = BABYLON.Vector3.Zero();
  45515. this._tempVector3 = BABYLON.Vector3.Zero();
  45516. this._tempVector4 = BABYLON.Vector3.Zero();
  45517. this._edge = BABYLON.Vector3.Zero();
  45518. this._baseToVertex = BABYLON.Vector3.Zero();
  45519. this._destinationPoint = BABYLON.Vector3.Zero();
  45520. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45521. this._displacementVector = BABYLON.Vector3.Zero();
  45522. this._radius = BABYLON.Vector3.One();
  45523. this._retry = 0;
  45524. this._basePointWorld = BABYLON.Vector3.Zero();
  45525. this._velocityWorld = BABYLON.Vector3.Zero();
  45526. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45527. this._collisionMask = -1;
  45528. }
  45529. Object.defineProperty(Collider.prototype, "collisionMask", {
  45530. get: function () {
  45531. return this._collisionMask;
  45532. },
  45533. set: function (mask) {
  45534. this._collisionMask = !isNaN(mask) ? mask : -1;
  45535. },
  45536. enumerable: true,
  45537. configurable: true
  45538. });
  45539. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45540. /**
  45541. * Gets the plane normal used to compute the sliding response (in local space)
  45542. */
  45543. get: function () {
  45544. return this._slidePlaneNormal;
  45545. },
  45546. enumerable: true,
  45547. configurable: true
  45548. });
  45549. // Methods
  45550. Collider.prototype._initialize = function (source, dir, e) {
  45551. this._velocity = dir;
  45552. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45553. this._basePoint = source;
  45554. source.multiplyToRef(this._radius, this._basePointWorld);
  45555. dir.multiplyToRef(this._radius, this._velocityWorld);
  45556. this._velocityWorldLength = this._velocityWorld.length();
  45557. this._epsilon = e;
  45558. this.collisionFound = false;
  45559. };
  45560. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45561. pa.subtractToRef(point, this._tempVector);
  45562. pb.subtractToRef(point, this._tempVector2);
  45563. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45564. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45565. if (d < 0)
  45566. return false;
  45567. pc.subtractToRef(point, this._tempVector3);
  45568. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45569. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45570. if (d < 0)
  45571. return false;
  45572. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45573. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45574. return d >= 0;
  45575. };
  45576. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45577. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45578. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45579. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45580. return false;
  45581. }
  45582. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45583. return false;
  45584. return true;
  45585. };
  45586. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45587. var t0;
  45588. var embeddedInPlane = false;
  45589. //defensive programming, actually not needed.
  45590. if (!trianglePlaneArray) {
  45591. trianglePlaneArray = [];
  45592. }
  45593. if (!trianglePlaneArray[faceIndex]) {
  45594. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45595. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45596. }
  45597. var trianglePlane = trianglePlaneArray[faceIndex];
  45598. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45599. return;
  45600. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45601. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45602. if (normalDotVelocity == 0) {
  45603. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45604. return;
  45605. embeddedInPlane = true;
  45606. t0 = 0;
  45607. }
  45608. else {
  45609. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45610. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45611. if (t0 > t1) {
  45612. var temp = t1;
  45613. t1 = t0;
  45614. t0 = temp;
  45615. }
  45616. if (t0 > 1.0 || t1 < 0.0)
  45617. return;
  45618. if (t0 < 0)
  45619. t0 = 0;
  45620. if (t0 > 1.0)
  45621. t0 = 1.0;
  45622. }
  45623. this._collisionPoint.copyFromFloats(0, 0, 0);
  45624. var found = false;
  45625. var t = 1.0;
  45626. if (!embeddedInPlane) {
  45627. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45628. this._velocity.scaleToRef(t0, this._tempVector);
  45629. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45630. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45631. found = true;
  45632. t = t0;
  45633. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45634. }
  45635. }
  45636. if (!found) {
  45637. var velocitySquaredLength = this._velocity.lengthSquared();
  45638. var a = velocitySquaredLength;
  45639. this._basePoint.subtractToRef(p1, this._tempVector);
  45640. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45641. var c = this._tempVector.lengthSquared() - 1.0;
  45642. var lowestRoot = getLowestRoot(a, b, c, t);
  45643. if (lowestRoot.found) {
  45644. t = lowestRoot.root;
  45645. found = true;
  45646. this._collisionPoint.copyFrom(p1);
  45647. }
  45648. this._basePoint.subtractToRef(p2, this._tempVector);
  45649. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45650. c = this._tempVector.lengthSquared() - 1.0;
  45651. lowestRoot = getLowestRoot(a, b, c, t);
  45652. if (lowestRoot.found) {
  45653. t = lowestRoot.root;
  45654. found = true;
  45655. this._collisionPoint.copyFrom(p2);
  45656. }
  45657. this._basePoint.subtractToRef(p3, this._tempVector);
  45658. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45659. c = this._tempVector.lengthSquared() - 1.0;
  45660. lowestRoot = getLowestRoot(a, b, c, t);
  45661. if (lowestRoot.found) {
  45662. t = lowestRoot.root;
  45663. found = true;
  45664. this._collisionPoint.copyFrom(p3);
  45665. }
  45666. p2.subtractToRef(p1, this._edge);
  45667. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45668. var edgeSquaredLength = this._edge.lengthSquared();
  45669. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45670. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45671. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45672. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45673. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45674. lowestRoot = getLowestRoot(a, b, c, t);
  45675. if (lowestRoot.found) {
  45676. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45677. if (f >= 0.0 && f <= 1.0) {
  45678. t = lowestRoot.root;
  45679. found = true;
  45680. this._edge.scaleInPlace(f);
  45681. p1.addToRef(this._edge, this._collisionPoint);
  45682. }
  45683. }
  45684. p3.subtractToRef(p2, this._edge);
  45685. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45686. edgeSquaredLength = this._edge.lengthSquared();
  45687. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45688. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45689. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45690. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45691. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45692. lowestRoot = getLowestRoot(a, b, c, t);
  45693. if (lowestRoot.found) {
  45694. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45695. if (f >= 0.0 && f <= 1.0) {
  45696. t = lowestRoot.root;
  45697. found = true;
  45698. this._edge.scaleInPlace(f);
  45699. p2.addToRef(this._edge, this._collisionPoint);
  45700. }
  45701. }
  45702. p1.subtractToRef(p3, this._edge);
  45703. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45704. edgeSquaredLength = this._edge.lengthSquared();
  45705. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45706. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45707. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45708. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45709. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45710. lowestRoot = getLowestRoot(a, b, c, t);
  45711. if (lowestRoot.found) {
  45712. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45713. if (f >= 0.0 && f <= 1.0) {
  45714. t = lowestRoot.root;
  45715. found = true;
  45716. this._edge.scaleInPlace(f);
  45717. p3.addToRef(this._edge, this._collisionPoint);
  45718. }
  45719. }
  45720. }
  45721. if (found) {
  45722. var distToCollision = t * this._velocity.length();
  45723. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45724. if (!this.intersectionPoint) {
  45725. this.intersectionPoint = this._collisionPoint.clone();
  45726. }
  45727. else {
  45728. this.intersectionPoint.copyFrom(this._collisionPoint);
  45729. }
  45730. this._nearestDistance = distToCollision;
  45731. this.collisionFound = true;
  45732. }
  45733. }
  45734. };
  45735. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45736. for (var i = indexStart; i < indexEnd; i += 3) {
  45737. var p1 = pts[indices[i] - decal];
  45738. var p2 = pts[indices[i + 1] - decal];
  45739. var p3 = pts[indices[i + 2] - decal];
  45740. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45741. }
  45742. };
  45743. Collider.prototype._getResponse = function (pos, vel) {
  45744. pos.addToRef(vel, this._destinationPoint);
  45745. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45746. this._basePoint.addToRef(vel, pos);
  45747. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45748. this._slidePlaneNormal.normalize();
  45749. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45750. pos.addInPlace(this._displacementVector);
  45751. this.intersectionPoint.addInPlace(this._displacementVector);
  45752. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45753. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45754. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45755. };
  45756. return Collider;
  45757. }());
  45758. BABYLON.Collider = Collider;
  45759. })(BABYLON || (BABYLON = {}));
  45760. //# sourceMappingURL=babylon.collider.js.map
  45761. var BABYLON;
  45762. (function (BABYLON) {
  45763. //WebWorker code will be inserted to this variable.
  45764. BABYLON.CollisionWorker = "";
  45765. var WorkerTaskType;
  45766. (function (WorkerTaskType) {
  45767. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45768. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45769. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45770. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45771. var WorkerReplyType;
  45772. (function (WorkerReplyType) {
  45773. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45774. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45775. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45776. var CollisionCoordinatorWorker = /** @class */ (function () {
  45777. function CollisionCoordinatorWorker() {
  45778. var _this = this;
  45779. this._scaledPosition = BABYLON.Vector3.Zero();
  45780. this._scaledVelocity = BABYLON.Vector3.Zero();
  45781. this.onMeshUpdated = function (transformNode) {
  45782. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45783. };
  45784. this.onGeometryUpdated = function (geometry) {
  45785. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45786. };
  45787. this._afterRender = function () {
  45788. if (!_this._init)
  45789. return;
  45790. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45791. return;
  45792. }
  45793. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45794. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45795. if (_this._runningUpdated > 4) {
  45796. return;
  45797. }
  45798. ++_this._runningUpdated;
  45799. var payload = {
  45800. updatedMeshes: _this._addUpdateMeshesList,
  45801. updatedGeometries: _this._addUpdateGeometriesList,
  45802. removedGeometries: _this._toRemoveGeometryArray,
  45803. removedMeshes: _this._toRemoveMeshesArray
  45804. };
  45805. var message = {
  45806. payload: payload,
  45807. taskType: WorkerTaskType.UPDATE
  45808. };
  45809. var serializable = [];
  45810. for (var id in payload.updatedGeometries) {
  45811. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45812. //prepare transferables
  45813. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45814. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45815. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45816. }
  45817. }
  45818. _this._worker.postMessage(message, serializable);
  45819. _this._addUpdateMeshesList = {};
  45820. _this._addUpdateGeometriesList = {};
  45821. _this._toRemoveGeometryArray = [];
  45822. _this._toRemoveMeshesArray = [];
  45823. };
  45824. this._onMessageFromWorker = function (e) {
  45825. var returnData = e.data;
  45826. if (returnData.error != WorkerReplyType.SUCCESS) {
  45827. //TODO what errors can be returned from the worker?
  45828. BABYLON.Tools.Warn("error returned from worker!");
  45829. return;
  45830. }
  45831. switch (returnData.taskType) {
  45832. case WorkerTaskType.INIT:
  45833. _this._init = true;
  45834. //Update the worked with ALL of the scene's current state
  45835. _this._scene.meshes.forEach(function (mesh) {
  45836. _this.onMeshAdded(mesh);
  45837. });
  45838. _this._scene.getGeometries().forEach(function (geometry) {
  45839. _this.onGeometryAdded(geometry);
  45840. });
  45841. break;
  45842. case WorkerTaskType.UPDATE:
  45843. _this._runningUpdated--;
  45844. break;
  45845. case WorkerTaskType.COLLIDE:
  45846. var returnPayload = returnData.payload;
  45847. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45848. return;
  45849. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45850. if (callback) {
  45851. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45852. if (mesh) {
  45853. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45854. }
  45855. }
  45856. //cleanup
  45857. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45858. break;
  45859. }
  45860. };
  45861. this._collisionsCallbackArray = [];
  45862. this._init = false;
  45863. this._runningUpdated = 0;
  45864. this._addUpdateMeshesList = {};
  45865. this._addUpdateGeometriesList = {};
  45866. this._toRemoveGeometryArray = [];
  45867. this._toRemoveMeshesArray = [];
  45868. }
  45869. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45870. if (!this._init)
  45871. return;
  45872. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45873. return;
  45874. position.divideToRef(collider._radius, this._scaledPosition);
  45875. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45876. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45877. var payload = {
  45878. collider: {
  45879. position: this._scaledPosition.asArray(),
  45880. velocity: this._scaledVelocity.asArray(),
  45881. radius: collider._radius.asArray()
  45882. },
  45883. collisionId: collisionIndex,
  45884. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45885. maximumRetry: maximumRetry
  45886. };
  45887. var message = {
  45888. payload: payload,
  45889. taskType: WorkerTaskType.COLLIDE
  45890. };
  45891. this._worker.postMessage(message);
  45892. };
  45893. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45894. this._scene = scene;
  45895. this._scene.registerAfterRender(this._afterRender);
  45896. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45897. this._worker = new Worker(workerUrl);
  45898. this._worker.onmessage = this._onMessageFromWorker;
  45899. var message = {
  45900. payload: {},
  45901. taskType: WorkerTaskType.INIT
  45902. };
  45903. this._worker.postMessage(message);
  45904. };
  45905. CollisionCoordinatorWorker.prototype.destroy = function () {
  45906. this._scene.unregisterAfterRender(this._afterRender);
  45907. this._worker.terminate();
  45908. };
  45909. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45910. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45911. this.onMeshUpdated(mesh);
  45912. };
  45913. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45914. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45915. };
  45916. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45917. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45918. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45919. this.onGeometryUpdated(geometry);
  45920. };
  45921. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45922. this._toRemoveGeometryArray.push(geometry.id);
  45923. };
  45924. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45925. var submeshes = [];
  45926. if (mesh.subMeshes) {
  45927. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45928. var boundingInfo = sm.getBoundingInfo();
  45929. return {
  45930. position: idx,
  45931. verticesStart: sm.verticesStart,
  45932. verticesCount: sm.verticesCount,
  45933. indexStart: sm.indexStart,
  45934. indexCount: sm.indexCount,
  45935. hasMaterial: !!sm.getMaterial(),
  45936. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45937. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45938. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45939. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45940. };
  45941. });
  45942. }
  45943. var geometryId = null;
  45944. if (mesh instanceof BABYLON.Mesh) {
  45945. var geometry = mesh.geometry;
  45946. geometryId = geometry ? geometry.id : null;
  45947. }
  45948. else if (mesh instanceof BABYLON.InstancedMesh) {
  45949. var geometry = mesh.sourceMesh.geometry;
  45950. geometryId = geometry ? geometry.id : null;
  45951. }
  45952. var boundingInfo = mesh.getBoundingInfo();
  45953. return {
  45954. uniqueId: mesh.uniqueId,
  45955. id: mesh.id,
  45956. name: mesh.name,
  45957. geometryId: geometryId,
  45958. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45959. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45960. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45961. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45962. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45963. subMeshes: submeshes,
  45964. checkCollisions: mesh.checkCollisions
  45965. };
  45966. };
  45967. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45968. return {
  45969. id: geometry.id,
  45970. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45971. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45972. indices: new Uint32Array(geometry.getIndices() || []),
  45973. };
  45974. };
  45975. return CollisionCoordinatorWorker;
  45976. }());
  45977. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45978. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45979. function CollisionCoordinatorLegacy() {
  45980. this._scaledPosition = BABYLON.Vector3.Zero();
  45981. this._scaledVelocity = BABYLON.Vector3.Zero();
  45982. this._finalPosition = BABYLON.Vector3.Zero();
  45983. }
  45984. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45985. position.divideToRef(collider._radius, this._scaledPosition);
  45986. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45987. collider.collidedMesh = null;
  45988. collider._retry = 0;
  45989. collider._initialVelocity = this._scaledVelocity;
  45990. collider._initialPosition = this._scaledPosition;
  45991. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45992. this._finalPosition.multiplyInPlace(collider._radius);
  45993. //run the callback
  45994. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45995. };
  45996. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45997. this._scene = scene;
  45998. };
  45999. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46000. //Legacy need no destruction method.
  46001. };
  46002. //No update in legacy mode
  46003. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46004. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46005. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46006. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46007. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46008. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46009. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46010. if (excludedMesh === void 0) { excludedMesh = null; }
  46011. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46012. if (collider._retry >= maximumRetry) {
  46013. finalPosition.copyFrom(position);
  46014. return;
  46015. }
  46016. // Check if this is a mesh else camera or -1
  46017. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46018. collider._initialize(position, velocity, closeDistance);
  46019. // Check all meshes
  46020. for (var index = 0; index < this._scene.meshes.length; index++) {
  46021. var mesh = this._scene.meshes[index];
  46022. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46023. mesh._checkCollision(collider);
  46024. }
  46025. }
  46026. if (!collider.collisionFound) {
  46027. position.addToRef(velocity, finalPosition);
  46028. return;
  46029. }
  46030. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46031. collider._getResponse(position, velocity);
  46032. }
  46033. if (velocity.length() <= closeDistance) {
  46034. finalPosition.copyFrom(position);
  46035. return;
  46036. }
  46037. collider._retry++;
  46038. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46039. };
  46040. return CollisionCoordinatorLegacy;
  46041. }());
  46042. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46043. })(BABYLON || (BABYLON = {}));
  46044. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46045. var BABYLON;
  46046. (function (BABYLON) {
  46047. var Particle = /** @class */ (function () {
  46048. function Particle(particleSystem) {
  46049. this.particleSystem = particleSystem;
  46050. this.position = BABYLON.Vector3.Zero();
  46051. this.direction = BABYLON.Vector3.Zero();
  46052. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46053. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46054. this.lifeTime = 1.0;
  46055. this.age = 0;
  46056. this.size = 0;
  46057. this.angle = 0;
  46058. this.angularSpeed = 0;
  46059. this._currentFrameCounter = 0;
  46060. this.cellIndex = 0;
  46061. if (!this.particleSystem.isAnimationSheetEnabled) {
  46062. return;
  46063. }
  46064. this.cellIndex = this.particleSystem.startSpriteCellID;
  46065. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46066. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46067. }
  46068. else {
  46069. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46070. }
  46071. }
  46072. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46073. // (ageOffset / scaledUpdateSpeed) / available cells
  46074. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46075. this._currentFrameCounter += scaledUpdateSpeed;
  46076. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46077. this._currentFrameCounter = 0;
  46078. this.cellIndex++;
  46079. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46080. this.cellIndex = this.particleSystem.endSpriteCellID;
  46081. }
  46082. }
  46083. };
  46084. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46085. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46086. this.cellIndex++;
  46087. this._currentFrameCounter = 0;
  46088. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46089. if (this.particleSystem.spriteCellLoop) {
  46090. this.cellIndex = this.particleSystem.startSpriteCellID;
  46091. }
  46092. else {
  46093. this.cellIndex = this.particleSystem.endSpriteCellID;
  46094. }
  46095. }
  46096. }
  46097. else {
  46098. this._currentFrameCounter++;
  46099. }
  46100. };
  46101. Particle.prototype.copyTo = function (other) {
  46102. other.position.copyFrom(this.position);
  46103. other.direction.copyFrom(this.direction);
  46104. other.color.copyFrom(this.color);
  46105. other.colorStep.copyFrom(this.colorStep);
  46106. other.lifeTime = this.lifeTime;
  46107. other.age = this.age;
  46108. other.size = this.size;
  46109. other.angle = this.angle;
  46110. other.angularSpeed = this.angularSpeed;
  46111. other.particleSystem = this.particleSystem;
  46112. other.cellIndex = this.cellIndex;
  46113. };
  46114. return Particle;
  46115. }());
  46116. BABYLON.Particle = Particle;
  46117. })(BABYLON || (BABYLON = {}));
  46118. //# sourceMappingURL=babylon.particle.js.map
  46119. var BABYLON;
  46120. (function (BABYLON) {
  46121. var ParticleSystem = /** @class */ (function () {
  46122. // end of sheet animation
  46123. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46124. if (customEffect === void 0) { customEffect = null; }
  46125. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46126. if (epsilon === void 0) { epsilon = 0.01; }
  46127. var _this = this;
  46128. this.name = name;
  46129. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46130. // Members
  46131. this.animations = [];
  46132. this.renderingGroupId = 0;
  46133. this.emitter = null;
  46134. this.emitRate = 10;
  46135. this.manualEmitCount = -1;
  46136. this.updateSpeed = 0.01;
  46137. this.targetStopDuration = 0;
  46138. this.disposeOnStop = false;
  46139. this.minEmitPower = 1;
  46140. this.maxEmitPower = 1;
  46141. this.minLifeTime = 1;
  46142. this.maxLifeTime = 1;
  46143. this.minSize = 1;
  46144. this.maxSize = 1;
  46145. this.minAngularSpeed = 0;
  46146. this.maxAngularSpeed = 0;
  46147. this.layerMask = 0x0FFFFFFF;
  46148. this.customShader = null;
  46149. this.preventAutoStart = false;
  46150. /**
  46151. * An event triggered when the system is disposed.
  46152. * @type {BABYLON.Observable}
  46153. */
  46154. this.onDisposeObservable = new BABYLON.Observable();
  46155. this.onAnimationEnd = null;
  46156. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46157. this.forceDepthWrite = false;
  46158. this.gravity = BABYLON.Vector3.Zero();
  46159. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46160. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46161. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46162. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46163. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46164. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46165. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46166. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46167. this.particles = new Array();
  46168. this._stockParticles = new Array();
  46169. this._newPartsExcess = 0;
  46170. this._vertexBuffers = {};
  46171. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46172. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46173. this._scaledDirection = BABYLON.Vector3.Zero();
  46174. this._scaledGravity = BABYLON.Vector3.Zero();
  46175. this._currentRenderId = -1;
  46176. this._started = false;
  46177. this._stopped = false;
  46178. this._actualFrame = 0;
  46179. // sheet animation
  46180. this.startSpriteCellID = 0;
  46181. this.endSpriteCellID = 0;
  46182. this.spriteCellLoop = true;
  46183. this.spriteCellChangeSpeed = 0;
  46184. this.spriteCellWidth = 0;
  46185. this.spriteCellHeight = 0;
  46186. this._vertexBufferSize = 11;
  46187. this.appendParticleVertexes = null;
  46188. this.id = name;
  46189. this._capacity = capacity;
  46190. this._epsilon = epsilon;
  46191. if (_isAnimationSheetEnabled) {
  46192. this._vertexBufferSize = 12;
  46193. }
  46194. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46195. this._customEffect = customEffect;
  46196. scene.particleSystems.push(this);
  46197. this._createIndexBuffer();
  46198. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46199. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46200. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46201. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46202. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46203. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46204. if (this._isAnimationSheetEnabled) {
  46205. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46206. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46207. }
  46208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46209. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46210. this._vertexBuffers["options"] = options;
  46211. // Default behaviors
  46212. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46213. this.updateFunction = function (particles) {
  46214. for (var index = 0; index < particles.length; index++) {
  46215. var particle = particles[index];
  46216. particle.age += _this._scaledUpdateSpeed;
  46217. if (particle.age >= particle.lifeTime) {
  46218. _this.recycleParticle(particle);
  46219. index--;
  46220. continue;
  46221. }
  46222. else {
  46223. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46224. particle.color.addInPlace(_this._scaledColorStep);
  46225. if (particle.color.a < 0)
  46226. particle.color.a = 0;
  46227. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46228. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46229. particle.position.addInPlace(_this._scaledDirection);
  46230. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46231. particle.direction.addInPlace(_this._scaledGravity);
  46232. if (_this._isAnimationSheetEnabled) {
  46233. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46234. }
  46235. }
  46236. }
  46237. };
  46238. }
  46239. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46240. set: function (callback) {
  46241. if (this._onDisposeObserver) {
  46242. this.onDisposeObservable.remove(this._onDisposeObserver);
  46243. }
  46244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46245. },
  46246. enumerable: true,
  46247. configurable: true
  46248. });
  46249. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46250. get: function () {
  46251. return this._isAnimationSheetEnabled;
  46252. },
  46253. enumerable: true,
  46254. configurable: true
  46255. });
  46256. ParticleSystem.prototype._createIndexBuffer = function () {
  46257. var indices = [];
  46258. var index = 0;
  46259. for (var count = 0; count < this._capacity; count++) {
  46260. indices.push(index);
  46261. indices.push(index + 1);
  46262. indices.push(index + 2);
  46263. indices.push(index);
  46264. indices.push(index + 2);
  46265. indices.push(index + 3);
  46266. index += 4;
  46267. }
  46268. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46269. };
  46270. ParticleSystem.prototype.recycleParticle = function (particle) {
  46271. var lastParticle = this.particles.pop();
  46272. if (lastParticle !== particle) {
  46273. lastParticle.copyTo(particle);
  46274. this._stockParticles.push(lastParticle);
  46275. }
  46276. };
  46277. ParticleSystem.prototype.getCapacity = function () {
  46278. return this._capacity;
  46279. };
  46280. ParticleSystem.prototype.isAlive = function () {
  46281. return this._alive;
  46282. };
  46283. ParticleSystem.prototype.isStarted = function () {
  46284. return this._started;
  46285. };
  46286. ParticleSystem.prototype.start = function () {
  46287. this._started = true;
  46288. this._stopped = false;
  46289. this._actualFrame = 0;
  46290. };
  46291. ParticleSystem.prototype.stop = function () {
  46292. this._stopped = true;
  46293. };
  46294. // animation sheet
  46295. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46296. var offset = index * this._vertexBufferSize;
  46297. this._vertexData[offset] = particle.position.x;
  46298. this._vertexData[offset + 1] = particle.position.y;
  46299. this._vertexData[offset + 2] = particle.position.z;
  46300. this._vertexData[offset + 3] = particle.color.r;
  46301. this._vertexData[offset + 4] = particle.color.g;
  46302. this._vertexData[offset + 5] = particle.color.b;
  46303. this._vertexData[offset + 6] = particle.color.a;
  46304. this._vertexData[offset + 7] = particle.angle;
  46305. this._vertexData[offset + 8] = particle.size;
  46306. this._vertexData[offset + 9] = offsetX;
  46307. this._vertexData[offset + 10] = offsetY;
  46308. };
  46309. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46310. if (offsetX === 0)
  46311. offsetX = this._epsilon;
  46312. else if (offsetX === 1)
  46313. offsetX = 1 - this._epsilon;
  46314. if (offsetY === 0)
  46315. offsetY = this._epsilon;
  46316. else if (offsetY === 1)
  46317. offsetY = 1 - this._epsilon;
  46318. var offset = index * this._vertexBufferSize;
  46319. this._vertexData[offset] = particle.position.x;
  46320. this._vertexData[offset + 1] = particle.position.y;
  46321. this._vertexData[offset + 2] = particle.position.z;
  46322. this._vertexData[offset + 3] = particle.color.r;
  46323. this._vertexData[offset + 4] = particle.color.g;
  46324. this._vertexData[offset + 5] = particle.color.b;
  46325. this._vertexData[offset + 6] = particle.color.a;
  46326. this._vertexData[offset + 7] = particle.angle;
  46327. this._vertexData[offset + 8] = particle.size;
  46328. this._vertexData[offset + 9] = offsetX;
  46329. this._vertexData[offset + 10] = offsetY;
  46330. this._vertexData[offset + 11] = particle.cellIndex;
  46331. };
  46332. ParticleSystem.prototype._update = function (newParticles) {
  46333. // Update current
  46334. this._alive = this.particles.length > 0;
  46335. this.updateFunction(this.particles);
  46336. // Add new ones
  46337. var worldMatrix;
  46338. if (this.emitter.position) {
  46339. var emitterMesh = this.emitter;
  46340. worldMatrix = emitterMesh.getWorldMatrix();
  46341. }
  46342. else {
  46343. var emitterPosition = this.emitter;
  46344. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46345. }
  46346. var particle;
  46347. for (var index = 0; index < newParticles; index++) {
  46348. if (this.particles.length === this._capacity) {
  46349. break;
  46350. }
  46351. if (this._stockParticles.length !== 0) {
  46352. particle = this._stockParticles.pop();
  46353. particle.age = 0;
  46354. particle.cellIndex = this.startSpriteCellID;
  46355. }
  46356. else {
  46357. particle = new BABYLON.Particle(this);
  46358. }
  46359. this.particles.push(particle);
  46360. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46361. if (this.startDirectionFunction) {
  46362. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46363. }
  46364. else {
  46365. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46366. }
  46367. if (this.startPositionFunction) {
  46368. this.startPositionFunction(worldMatrix, particle.position, particle);
  46369. }
  46370. else {
  46371. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46372. }
  46373. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46374. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46375. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46376. var step = ParticleSystem.randomNumber(0, 1.0);
  46377. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46378. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46379. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46380. }
  46381. };
  46382. ParticleSystem.prototype._getEffect = function () {
  46383. if (this._customEffect) {
  46384. return this._customEffect;
  46385. }
  46386. ;
  46387. var defines = [];
  46388. if (this._scene.clipPlane) {
  46389. defines.push("#define CLIPPLANE");
  46390. }
  46391. if (this._isAnimationSheetEnabled) {
  46392. defines.push("#define ANIMATESHEET");
  46393. }
  46394. // Effect
  46395. var join = defines.join("\n");
  46396. if (this._cachedDefines !== join) {
  46397. this._cachedDefines = join;
  46398. var attributesNamesOrOptions;
  46399. var effectCreationOption;
  46400. if (this._isAnimationSheetEnabled) {
  46401. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46402. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46403. }
  46404. else {
  46405. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46406. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46407. }
  46408. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46409. }
  46410. return this._effect;
  46411. };
  46412. ParticleSystem.prototype.animate = function () {
  46413. if (!this._started)
  46414. return;
  46415. var effect = this._getEffect();
  46416. // Check
  46417. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46418. return;
  46419. if (this._currentRenderId === this._scene.getRenderId()) {
  46420. return;
  46421. }
  46422. this._currentRenderId = this._scene.getRenderId();
  46423. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46424. // determine the number of particles we need to create
  46425. var newParticles;
  46426. if (this.manualEmitCount > -1) {
  46427. newParticles = this.manualEmitCount;
  46428. this._newPartsExcess = 0;
  46429. this.manualEmitCount = 0;
  46430. }
  46431. else {
  46432. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46433. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46434. }
  46435. if (this._newPartsExcess > 1.0) {
  46436. newParticles += this._newPartsExcess >> 0;
  46437. this._newPartsExcess -= this._newPartsExcess >> 0;
  46438. }
  46439. this._alive = false;
  46440. if (!this._stopped) {
  46441. this._actualFrame += this._scaledUpdateSpeed;
  46442. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46443. this.stop();
  46444. }
  46445. else {
  46446. newParticles = 0;
  46447. }
  46448. this._update(newParticles);
  46449. // Stopped?
  46450. if (this._stopped) {
  46451. if (!this._alive) {
  46452. this._started = false;
  46453. if (this.onAnimationEnd) {
  46454. this.onAnimationEnd();
  46455. }
  46456. if (this.disposeOnStop) {
  46457. this._scene._toBeDisposed.push(this);
  46458. }
  46459. }
  46460. }
  46461. // Animation sheet
  46462. if (this._isAnimationSheetEnabled) {
  46463. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46464. }
  46465. else {
  46466. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46467. }
  46468. // Update VBO
  46469. var offset = 0;
  46470. for (var index = 0; index < this.particles.length; index++) {
  46471. var particle = this.particles[index];
  46472. this.appendParticleVertexes(offset, particle);
  46473. offset += 4;
  46474. }
  46475. if (this._vertexBuffer) {
  46476. this._vertexBuffer.update(this._vertexData);
  46477. }
  46478. };
  46479. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46480. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46481. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46482. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46483. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46484. };
  46485. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46486. this._appendParticleVertex(offset++, particle, 0, 0);
  46487. this._appendParticleVertex(offset++, particle, 1, 0);
  46488. this._appendParticleVertex(offset++, particle, 1, 1);
  46489. this._appendParticleVertex(offset++, particle, 0, 1);
  46490. };
  46491. ParticleSystem.prototype.rebuild = function () {
  46492. this._createIndexBuffer();
  46493. if (this._vertexBuffer) {
  46494. this._vertexBuffer._rebuild();
  46495. }
  46496. };
  46497. ParticleSystem.prototype.render = function () {
  46498. var effect = this._getEffect();
  46499. // Check
  46500. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46501. return 0;
  46502. var engine = this._scene.getEngine();
  46503. // Render
  46504. engine.enableEffect(effect);
  46505. engine.setState(false);
  46506. var viewMatrix = this._scene.getViewMatrix();
  46507. effect.setTexture("diffuseSampler", this.particleTexture);
  46508. effect.setMatrix("view", viewMatrix);
  46509. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46510. if (this._isAnimationSheetEnabled) {
  46511. var baseSize = this.particleTexture.getBaseSize();
  46512. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46513. }
  46514. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46515. if (this._scene.clipPlane) {
  46516. var clipPlane = this._scene.clipPlane;
  46517. var invView = viewMatrix.clone();
  46518. invView.invert();
  46519. effect.setMatrix("invView", invView);
  46520. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46521. }
  46522. // VBOs
  46523. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46524. // Draw order
  46525. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46526. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46527. }
  46528. else {
  46529. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46530. }
  46531. if (this.forceDepthWrite) {
  46532. engine.setDepthWrite(true);
  46533. }
  46534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46535. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46536. return this.particles.length;
  46537. };
  46538. ParticleSystem.prototype.dispose = function () {
  46539. if (this._vertexBuffer) {
  46540. this._vertexBuffer.dispose();
  46541. this._vertexBuffer = null;
  46542. }
  46543. if (this._indexBuffer) {
  46544. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46545. this._indexBuffer = null;
  46546. }
  46547. if (this.particleTexture) {
  46548. this.particleTexture.dispose();
  46549. this.particleTexture = null;
  46550. }
  46551. // Remove from scene
  46552. var index = this._scene.particleSystems.indexOf(this);
  46553. if (index > -1) {
  46554. this._scene.particleSystems.splice(index, 1);
  46555. }
  46556. // Callback
  46557. this.onDisposeObservable.notifyObservers(this);
  46558. this.onDisposeObservable.clear();
  46559. };
  46560. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46561. if (radius === void 0) { radius = 1; }
  46562. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46563. this.particleEmitterType = particleEmitter;
  46564. return particleEmitter;
  46565. };
  46566. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46567. if (radius === void 0) { radius = 1; }
  46568. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46569. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46570. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46571. this.particleEmitterType = particleEmitter;
  46572. return particleEmitter;
  46573. };
  46574. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46575. if (radius === void 0) { radius = 1; }
  46576. if (angle === void 0) { angle = Math.PI / 4; }
  46577. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46578. this.particleEmitterType = particleEmitter;
  46579. return particleEmitter;
  46580. };
  46581. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  46582. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46583. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46584. this.direction1 = direction1;
  46585. this.direction2 = direction2;
  46586. this.minEmitBox = minEmitBox;
  46587. this.maxEmitBox = maxEmitBox;
  46588. this.particleEmitterType = particleEmitter;
  46589. return particleEmitter;
  46590. };
  46591. ParticleSystem.randomNumber = function (min, max) {
  46592. if (min === max) {
  46593. return (min);
  46594. }
  46595. var random = Math.random();
  46596. return ((random * (max - min)) + min);
  46597. };
  46598. // Clone
  46599. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46600. var custom = null;
  46601. var program = null;
  46602. if (this.customShader != null) {
  46603. program = this.customShader;
  46604. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46605. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46606. }
  46607. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46608. result.customShader = program;
  46609. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46610. if (newEmitter === undefined) {
  46611. newEmitter = this.emitter;
  46612. }
  46613. result.emitter = newEmitter;
  46614. if (this.particleTexture) {
  46615. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46616. }
  46617. if (!this.preventAutoStart) {
  46618. result.start();
  46619. }
  46620. return result;
  46621. };
  46622. ParticleSystem.prototype.serialize = function () {
  46623. var serializationObject = {};
  46624. serializationObject.name = this.name;
  46625. serializationObject.id = this.id;
  46626. // Emitter
  46627. if (this.emitter.position) {
  46628. var emitterMesh = this.emitter;
  46629. serializationObject.emitterId = emitterMesh.id;
  46630. }
  46631. else {
  46632. var emitterPosition = this.emitter;
  46633. serializationObject.emitter = emitterPosition.asArray();
  46634. }
  46635. serializationObject.capacity = this.getCapacity();
  46636. if (this.particleTexture) {
  46637. serializationObject.textureName = this.particleTexture.name;
  46638. }
  46639. // Animations
  46640. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46641. // Particle system
  46642. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46643. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46644. serializationObject.minSize = this.minSize;
  46645. serializationObject.maxSize = this.maxSize;
  46646. serializationObject.minEmitPower = this.minEmitPower;
  46647. serializationObject.maxEmitPower = this.maxEmitPower;
  46648. serializationObject.minLifeTime = this.minLifeTime;
  46649. serializationObject.maxLifeTime = this.maxLifeTime;
  46650. serializationObject.emitRate = this.emitRate;
  46651. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46652. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46653. serializationObject.gravity = this.gravity.asArray();
  46654. serializationObject.direction1 = this.direction1.asArray();
  46655. serializationObject.direction2 = this.direction2.asArray();
  46656. serializationObject.color1 = this.color1.asArray();
  46657. serializationObject.color2 = this.color2.asArray();
  46658. serializationObject.colorDead = this.colorDead.asArray();
  46659. serializationObject.updateSpeed = this.updateSpeed;
  46660. serializationObject.targetStopDuration = this.targetStopDuration;
  46661. serializationObject.textureMask = this.textureMask.asArray();
  46662. serializationObject.blendMode = this.blendMode;
  46663. serializationObject.customShader = this.customShader;
  46664. serializationObject.preventAutoStart = this.preventAutoStart;
  46665. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46666. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46667. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46668. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46669. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46670. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46671. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46672. return serializationObject;
  46673. };
  46674. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46675. var name = parsedParticleSystem.name;
  46676. var custom = null;
  46677. var program = null;
  46678. if (parsedParticleSystem.customShader) {
  46679. program = parsedParticleSystem.customShader;
  46680. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46681. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46682. }
  46683. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46684. particleSystem.customShader = program;
  46685. if (parsedParticleSystem.id) {
  46686. particleSystem.id = parsedParticleSystem.id;
  46687. }
  46688. // Auto start
  46689. if (parsedParticleSystem.preventAutoStart) {
  46690. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46691. }
  46692. // Texture
  46693. if (parsedParticleSystem.textureName) {
  46694. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46695. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46696. }
  46697. // Emitter
  46698. if (parsedParticleSystem.emitterId) {
  46699. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46700. }
  46701. else {
  46702. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46703. }
  46704. // Animations
  46705. if (parsedParticleSystem.animations) {
  46706. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46707. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46708. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46709. }
  46710. }
  46711. if (parsedParticleSystem.autoAnimate) {
  46712. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46713. }
  46714. // Particle system
  46715. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46716. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46717. particleSystem.minSize = parsedParticleSystem.minSize;
  46718. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46719. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46720. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46721. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46722. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46723. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46724. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46725. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46726. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46727. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46728. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46729. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46730. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46731. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46732. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46733. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46734. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46735. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46736. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46737. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46738. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46739. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46740. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46741. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46742. if (!particleSystem.preventAutoStart) {
  46743. particleSystem.start();
  46744. }
  46745. return particleSystem;
  46746. };
  46747. // Statics
  46748. ParticleSystem.BLENDMODE_ONEONE = 0;
  46749. ParticleSystem.BLENDMODE_STANDARD = 1;
  46750. return ParticleSystem;
  46751. }());
  46752. BABYLON.ParticleSystem = ParticleSystem;
  46753. })(BABYLON || (BABYLON = {}));
  46754. //# sourceMappingURL=babylon.particleSystem.js.map
  46755. var BABYLON;
  46756. (function (BABYLON) {
  46757. var BoxParticleEmitter = /** @class */ (function () {
  46758. // to be updated like the rest of emitters when breaking changes.
  46759. // all property should be come public variables and passed through constructor.
  46760. function BoxParticleEmitter(_particleSystem) {
  46761. this._particleSystem = _particleSystem;
  46762. }
  46763. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46764. get: function () {
  46765. return this._particleSystem.direction1;
  46766. },
  46767. set: function (value) {
  46768. this._particleSystem.direction1 = value;
  46769. },
  46770. enumerable: true,
  46771. configurable: true
  46772. });
  46773. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46774. get: function () {
  46775. return this._particleSystem.direction2;
  46776. },
  46777. set: function (value) {
  46778. this._particleSystem.direction2 = value;
  46779. },
  46780. enumerable: true,
  46781. configurable: true
  46782. });
  46783. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46784. get: function () {
  46785. return this._particleSystem.minEmitBox;
  46786. },
  46787. set: function (value) {
  46788. this._particleSystem.minEmitBox = value;
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46794. get: function () {
  46795. return this._particleSystem.maxEmitBox;
  46796. },
  46797. set: function (value) {
  46798. this._particleSystem.maxEmitBox = value;
  46799. },
  46800. enumerable: true,
  46801. configurable: true
  46802. });
  46803. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46804. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46805. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46806. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46807. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46808. };
  46809. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46810. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46811. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46812. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46813. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46814. };
  46815. return BoxParticleEmitter;
  46816. }());
  46817. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46818. })(BABYLON || (BABYLON = {}));
  46819. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46820. var BABYLON;
  46821. (function (BABYLON) {
  46822. var ConeParticleEmitter = /** @class */ (function () {
  46823. function ConeParticleEmitter(radius, angle) {
  46824. this.radius = radius;
  46825. this.angle = angle;
  46826. }
  46827. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46828. if (this.angle === 0) {
  46829. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46830. }
  46831. else {
  46832. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46833. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46834. var randX = Math.cos(phi) * Math.sin(theta);
  46835. var randY = Math.cos(theta);
  46836. var randZ = Math.sin(phi) * Math.sin(theta);
  46837. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46838. }
  46839. };
  46840. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46841. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46842. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46843. var randX = radius * Math.sin(s);
  46844. var randZ = radius * Math.cos(s);
  46845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46846. };
  46847. return ConeParticleEmitter;
  46848. }());
  46849. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46850. })(BABYLON || (BABYLON = {}));
  46851. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46852. var BABYLON;
  46853. (function (BABYLON) {
  46854. var SphereParticleEmitter = /** @class */ (function () {
  46855. function SphereParticleEmitter(radius) {
  46856. this.radius = radius;
  46857. }
  46858. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46859. // measure the direction Vector from the emitter to the particle.
  46860. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46861. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46862. };
  46863. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46864. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46865. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46866. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46867. var randY = this.radius * Math.cos(theta);
  46868. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46869. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46870. };
  46871. return SphereParticleEmitter;
  46872. }());
  46873. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46874. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46875. __extends(SphereDirectedParticleEmitter, _super);
  46876. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46877. var _this = _super.call(this, radius) || this;
  46878. _this.direction1 = direction1;
  46879. _this.direction2 = direction2;
  46880. return _this;
  46881. }
  46882. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46883. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46884. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46885. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46886. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46887. };
  46888. return SphereDirectedParticleEmitter;
  46889. }(SphereParticleEmitter));
  46890. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46891. })(BABYLON || (BABYLON = {}));
  46892. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46893. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46894. var BABYLON;
  46895. (function (BABYLON) {
  46896. var SolidParticle = /** @class */ (function () {
  46897. /**
  46898. * Creates a Solid Particle object.
  46899. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46900. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46901. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46902. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46903. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46904. * `shapeId` (integer) is the model shape identifier in the SPS.
  46905. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46906. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46907. */
  46908. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46909. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46910. this.idx = 0; // particle global index
  46911. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46912. this.position = BABYLON.Vector3.Zero(); // position
  46913. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46914. this.scaling = BABYLON.Vector3.One(); // scaling
  46915. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46916. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46917. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46918. this.alive = true; // alive
  46919. this.isVisible = true; // visibility
  46920. this._pos = 0; // index of this particle in the global "positions" array
  46921. this._ind = 0; // index of this particle in the global "indices" array
  46922. this.shapeId = 0; // model shape id
  46923. this.idxInShape = 0; // index of the particle in its shape id
  46924. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46925. this.idx = particleIndex;
  46926. this._pos = positionIndex;
  46927. this._ind = indiceIndex;
  46928. this._model = model;
  46929. this.shapeId = shapeId;
  46930. this.idxInShape = idxInShape;
  46931. this._sps = sps;
  46932. if (modelBoundingInfo) {
  46933. this._modelBoundingInfo = modelBoundingInfo;
  46934. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46935. }
  46936. }
  46937. Object.defineProperty(SolidParticle.prototype, "scale", {
  46938. /**
  46939. * legacy support, changed scale to scaling
  46940. */
  46941. get: function () {
  46942. return this.scaling;
  46943. },
  46944. set: function (scale) {
  46945. this.scaling = scale;
  46946. },
  46947. enumerable: true,
  46948. configurable: true
  46949. });
  46950. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46951. /**
  46952. * legacy support, changed quaternion to rotationQuaternion
  46953. */
  46954. get: function () {
  46955. return this.rotationQuaternion;
  46956. },
  46957. set: function (q) {
  46958. this.rotationQuaternion = q;
  46959. },
  46960. enumerable: true,
  46961. configurable: true
  46962. });
  46963. /**
  46964. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46965. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46966. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46967. */
  46968. SolidParticle.prototype.intersectsMesh = function (target) {
  46969. if (!this._boundingInfo || !target._boundingInfo) {
  46970. return false;
  46971. }
  46972. if (this._sps._bSphereOnly) {
  46973. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46974. }
  46975. return this._boundingInfo.intersects(target._boundingInfo, false);
  46976. };
  46977. return SolidParticle;
  46978. }());
  46979. BABYLON.SolidParticle = SolidParticle;
  46980. var ModelShape = /** @class */ (function () {
  46981. /**
  46982. * 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.
  46983. * SPS internal tool, don't use it manually.
  46984. */
  46985. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46986. this._indicesLength = 0; // length of the shape in the model indices array
  46987. this.shapeID = id;
  46988. this._shape = shape;
  46989. this._indicesLength = indicesLength;
  46990. this._shapeUV = shapeUV;
  46991. this._positionFunction = posFunction;
  46992. this._vertexFunction = vtxFunction;
  46993. }
  46994. return ModelShape;
  46995. }());
  46996. BABYLON.ModelShape = ModelShape;
  46997. var DepthSortedParticle = /** @class */ (function () {
  46998. function DepthSortedParticle() {
  46999. this.ind = 0; // index of the particle in the "indices" array
  47000. this.indicesLength = 0; // length of the particle shape in the "indices" array
  47001. this.sqDistance = 0.0; // squared distance from the particle to the camera
  47002. }
  47003. return DepthSortedParticle;
  47004. }());
  47005. BABYLON.DepthSortedParticle = DepthSortedParticle;
  47006. })(BABYLON || (BABYLON = {}));
  47007. //# sourceMappingURL=babylon.solidParticle.js.map
  47008. var BABYLON;
  47009. (function (BABYLON) {
  47010. /**
  47011. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47012. */
  47013. var SolidParticleSystem = /** @class */ (function () {
  47014. /**
  47015. * Creates a SPS (Solid Particle System) object.
  47016. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47017. * `scene` (Scene) is the scene in which the SPS is added.
  47018. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47019. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47020. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47021. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47022. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47023. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47024. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47025. */
  47026. function SolidParticleSystem(name, scene, options) {
  47027. // public members
  47028. /**
  47029. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47030. * Example : var p = SPS.particles[i];
  47031. */
  47032. this.particles = new Array();
  47033. /**
  47034. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47035. */
  47036. this.nbParticles = 0;
  47037. /**
  47038. * If the particles must ever face the camera (default false). Useful for planar particles.
  47039. */
  47040. this.billboard = false;
  47041. /**
  47042. * Recompute normals when adding a shape
  47043. */
  47044. this.recomputeNormals = true;
  47045. /**
  47046. * This a counter ofr your own usage. It's not set by any SPS functions.
  47047. */
  47048. this.counter = 0;
  47049. /**
  47050. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47051. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47052. */
  47053. this.vars = {};
  47054. this._positions = new Array();
  47055. this._indices = new Array();
  47056. this._normals = new Array();
  47057. this._colors = new Array();
  47058. this._uvs = new Array();
  47059. this._index = 0; // indices index
  47060. this._updatable = true;
  47061. this._pickable = false;
  47062. this._isVisibilityBoxLocked = false;
  47063. this._alwaysVisible = false;
  47064. this._depthSort = false;
  47065. this._shapeCounter = 0;
  47066. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47067. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47068. this._computeParticleColor = true;
  47069. this._computeParticleTexture = true;
  47070. this._computeParticleRotation = true;
  47071. this._computeParticleVertex = false;
  47072. this._computeBoundingBox = false;
  47073. this._depthSortParticles = true;
  47074. this._cam_axisZ = BABYLON.Vector3.Zero();
  47075. this._cam_axisY = BABYLON.Vector3.Zero();
  47076. this._cam_axisX = BABYLON.Vector3.Zero();
  47077. this._axisZ = BABYLON.Axis.Z;
  47078. this._camDir = BABYLON.Vector3.Zero();
  47079. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47080. this._rotMatrix = new BABYLON.Matrix();
  47081. this._invertMatrix = new BABYLON.Matrix();
  47082. this._rotated = BABYLON.Vector3.Zero();
  47083. this._quaternion = new BABYLON.Quaternion();
  47084. this._vertex = BABYLON.Vector3.Zero();
  47085. this._normal = BABYLON.Vector3.Zero();
  47086. this._yaw = 0.0;
  47087. this._pitch = 0.0;
  47088. this._roll = 0.0;
  47089. this._halfroll = 0.0;
  47090. this._halfpitch = 0.0;
  47091. this._halfyaw = 0.0;
  47092. this._sinRoll = 0.0;
  47093. this._cosRoll = 0.0;
  47094. this._sinPitch = 0.0;
  47095. this._cosPitch = 0.0;
  47096. this._sinYaw = 0.0;
  47097. this._cosYaw = 0.0;
  47098. this._mustUnrotateFixedNormals = false;
  47099. this._minimum = BABYLON.Tmp.Vector3[0];
  47100. this._maximum = BABYLON.Tmp.Vector3[1];
  47101. this._minBbox = BABYLON.Tmp.Vector3[4];
  47102. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47103. this._particlesIntersect = false;
  47104. this._depthSortFunction = function (p1, p2) {
  47105. return (p2.sqDistance - p1.sqDistance);
  47106. };
  47107. this._needs32Bits = false;
  47108. this._bSphereOnly = false;
  47109. this._bSphereRadiusFactor = 1.0;
  47110. this.name = name;
  47111. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47112. this._camera = scene.activeCamera;
  47113. this._pickable = options ? options.isPickable : false;
  47114. this._depthSort = options ? options.enableDepthSort : false;
  47115. this._particlesIntersect = options ? options.particleIntersection : false;
  47116. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47117. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47118. if (options && options.updatable) {
  47119. this._updatable = options.updatable;
  47120. }
  47121. else {
  47122. this._updatable = true;
  47123. }
  47124. if (this._pickable) {
  47125. this.pickedParticles = [];
  47126. }
  47127. if (this._depthSort) {
  47128. this.depthSortedParticles = [];
  47129. }
  47130. }
  47131. /**
  47132. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47133. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47134. */
  47135. SolidParticleSystem.prototype.buildMesh = function () {
  47136. if (this.nbParticles === 0) {
  47137. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47138. this.addShape(triangle, 1);
  47139. triangle.dispose();
  47140. }
  47141. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47142. this._positions32 = new Float32Array(this._positions);
  47143. this._uvs32 = new Float32Array(this._uvs);
  47144. this._colors32 = new Float32Array(this._colors);
  47145. if (this.recomputeNormals) {
  47146. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47147. }
  47148. this._normals32 = new Float32Array(this._normals);
  47149. this._fixedNormal32 = new Float32Array(this._normals);
  47150. if (this._mustUnrotateFixedNormals) {
  47151. this._unrotateFixedNormals();
  47152. }
  47153. var vertexData = new BABYLON.VertexData();
  47154. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47155. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47156. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47157. if (this._uvs32) {
  47158. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47159. ;
  47160. }
  47161. if (this._colors32) {
  47162. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47163. }
  47164. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47165. vertexData.applyToMesh(mesh, this._updatable);
  47166. this.mesh = mesh;
  47167. this.mesh.isPickable = this._pickable;
  47168. // free memory
  47169. if (!this._depthSort) {
  47170. this._indices = null;
  47171. }
  47172. this._positions = null;
  47173. this._normals = null;
  47174. this._uvs = null;
  47175. this._colors = null;
  47176. if (!this._updatable) {
  47177. this.particles.length = 0;
  47178. }
  47179. return mesh;
  47180. };
  47181. /**
  47182. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47183. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47184. * Thus the particles generated from `digest()` have their property `position` set yet.
  47185. * `mesh` ( Mesh ) is the mesh to be digested
  47186. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47187. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47188. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47189. */
  47190. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47191. var size = (options && options.facetNb) || 1;
  47192. var number = (options && options.number) || 0;
  47193. var delta = (options && options.delta) || 0;
  47194. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47195. var meshInd = mesh.getIndices();
  47196. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47197. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47198. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47199. var f = 0; // facet counter
  47200. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47201. // compute size from number
  47202. if (number) {
  47203. number = (number > totalFacets) ? totalFacets : number;
  47204. size = Math.round(totalFacets / number);
  47205. delta = 0;
  47206. }
  47207. else {
  47208. size = (size > totalFacets) ? totalFacets : size;
  47209. }
  47210. var facetPos = []; // submesh positions
  47211. var facetInd = []; // submesh indices
  47212. var facetUV = []; // submesh UV
  47213. var facetCol = []; // submesh colors
  47214. var barycenter = BABYLON.Tmp.Vector3[0];
  47215. var sizeO = size;
  47216. while (f < totalFacets) {
  47217. size = sizeO + Math.floor((1 + delta) * Math.random());
  47218. if (f > totalFacets - size) {
  47219. size = totalFacets - f;
  47220. }
  47221. // reset temp arrays
  47222. facetPos.length = 0;
  47223. facetInd.length = 0;
  47224. facetUV.length = 0;
  47225. facetCol.length = 0;
  47226. // iterate over "size" facets
  47227. var fi = 0;
  47228. for (var j = f * 3; j < (f + size) * 3; j++) {
  47229. facetInd.push(fi);
  47230. var i = meshInd[j];
  47231. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47232. if (meshUV) {
  47233. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47234. }
  47235. if (meshCol) {
  47236. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47237. }
  47238. fi++;
  47239. }
  47240. // create a model shape for each single particle
  47241. var idx = this.nbParticles;
  47242. var shape = this._posToShape(facetPos);
  47243. var shapeUV = this._uvsToShapeUV(facetUV);
  47244. // compute the barycenter of the shape
  47245. var v;
  47246. for (v = 0; v < shape.length; v++) {
  47247. barycenter.addInPlace(shape[v]);
  47248. }
  47249. barycenter.scaleInPlace(1 / shape.length);
  47250. // shift the shape from its barycenter to the origin
  47251. for (v = 0; v < shape.length; v++) {
  47252. shape[v].subtractInPlace(barycenter);
  47253. }
  47254. var bInfo;
  47255. if (this._particlesIntersect) {
  47256. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47257. }
  47258. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47259. // add the particle in the SPS
  47260. var currentPos = this._positions.length;
  47261. var currentInd = this._indices.length;
  47262. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47263. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47264. // initialize the particle position
  47265. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47266. this._index += shape.length;
  47267. idx++;
  47268. this.nbParticles++;
  47269. this._shapeCounter++;
  47270. f += size;
  47271. }
  47272. return this;
  47273. };
  47274. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47275. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47276. var index = 0;
  47277. var idx = 0;
  47278. for (var p = 0; p < this.particles.length; p++) {
  47279. this._particle = this.particles[p];
  47280. this._shape = this._particle._model._shape;
  47281. if (this._particle.rotationQuaternion) {
  47282. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47283. }
  47284. else {
  47285. this._yaw = this._particle.rotation.y;
  47286. this._pitch = this._particle.rotation.x;
  47287. this._roll = this._particle.rotation.z;
  47288. this._quaternionRotationYPR();
  47289. }
  47290. this._quaternionToRotationMatrix();
  47291. this._rotMatrix.invertToRef(this._invertMatrix);
  47292. for (var pt = 0; pt < this._shape.length; pt++) {
  47293. idx = index + pt * 3;
  47294. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47295. this._fixedNormal32[idx] = this._normal.x;
  47296. this._fixedNormal32[idx + 1] = this._normal.y;
  47297. this._fixedNormal32[idx + 2] = this._normal.z;
  47298. }
  47299. index = idx + 3;
  47300. }
  47301. };
  47302. //reset copy
  47303. SolidParticleSystem.prototype._resetCopy = function () {
  47304. this._copy.position.x = 0;
  47305. this._copy.position.y = 0;
  47306. this._copy.position.z = 0;
  47307. this._copy.rotation.x = 0;
  47308. this._copy.rotation.y = 0;
  47309. this._copy.rotation.z = 0;
  47310. this._copy.rotationQuaternion = null;
  47311. this._copy.scaling.x = 1.0;
  47312. this._copy.scaling.y = 1.0;
  47313. this._copy.scaling.z = 1.0;
  47314. this._copy.uvs.x = 0;
  47315. this._copy.uvs.y = 0;
  47316. this._copy.uvs.z = 1.0;
  47317. this._copy.uvs.w = 1.0;
  47318. this._copy.color = null;
  47319. };
  47320. // _meshBuilder : inserts the shape model in the global SPS mesh
  47321. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47322. var i;
  47323. var u = 0;
  47324. var c = 0;
  47325. var n = 0;
  47326. this._resetCopy();
  47327. if (options && options.positionFunction) {
  47328. options.positionFunction(this._copy, idx, idxInShape);
  47329. this._mustUnrotateFixedNormals = true;
  47330. }
  47331. if (this._copy.rotationQuaternion) {
  47332. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47333. }
  47334. else {
  47335. this._yaw = this._copy.rotation.y;
  47336. this._pitch = this._copy.rotation.x;
  47337. this._roll = this._copy.rotation.z;
  47338. this._quaternionRotationYPR();
  47339. }
  47340. this._quaternionToRotationMatrix();
  47341. for (i = 0; i < shape.length; i++) {
  47342. this._vertex.x = shape[i].x;
  47343. this._vertex.y = shape[i].y;
  47344. this._vertex.z = shape[i].z;
  47345. if (options && options.vertexFunction) {
  47346. options.vertexFunction(this._copy, this._vertex, i);
  47347. }
  47348. this._vertex.x *= this._copy.scaling.x;
  47349. this._vertex.y *= this._copy.scaling.y;
  47350. this._vertex.z *= this._copy.scaling.z;
  47351. this._vertex.x += this._copy.pivot.x;
  47352. this._vertex.y += this._copy.pivot.y;
  47353. this._vertex.z += this._copy.pivot.z;
  47354. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47355. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47356. if (meshUV) {
  47357. 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);
  47358. u += 2;
  47359. }
  47360. if (this._copy.color) {
  47361. this._color = this._copy.color;
  47362. }
  47363. else if (meshCol && meshCol[c] !== undefined) {
  47364. this._color.r = meshCol[c];
  47365. this._color.g = meshCol[c + 1];
  47366. this._color.b = meshCol[c + 2];
  47367. this._color.a = meshCol[c + 3];
  47368. }
  47369. else {
  47370. this._color.r = 1.0;
  47371. this._color.g = 1.0;
  47372. this._color.b = 1.0;
  47373. this._color.a = 1.0;
  47374. }
  47375. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47376. c += 4;
  47377. if (!this.recomputeNormals && meshNor) {
  47378. this._normal.x = meshNor[n];
  47379. this._normal.y = meshNor[n + 1];
  47380. this._normal.z = meshNor[n + 2];
  47381. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47382. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47383. n += 3;
  47384. }
  47385. }
  47386. for (i = 0; i < meshInd.length; i++) {
  47387. var current_ind = p + meshInd[i];
  47388. indices.push(current_ind);
  47389. if (current_ind > 65535) {
  47390. this._needs32Bits = true;
  47391. }
  47392. }
  47393. if (this._pickable) {
  47394. var nbfaces = meshInd.length / 3;
  47395. for (i = 0; i < nbfaces; i++) {
  47396. this.pickedParticles.push({ idx: idx, faceId: i });
  47397. }
  47398. }
  47399. if (this._depthSort) {
  47400. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47401. }
  47402. return this._copy;
  47403. };
  47404. // returns a shape array from positions array
  47405. SolidParticleSystem.prototype._posToShape = function (positions) {
  47406. var shape = [];
  47407. for (var i = 0; i < positions.length; i += 3) {
  47408. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47409. }
  47410. return shape;
  47411. };
  47412. // returns a shapeUV array from a Vector4 uvs
  47413. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47414. var shapeUV = [];
  47415. if (uvs) {
  47416. for (var i = 0; i < uvs.length; i++)
  47417. shapeUV.push(uvs[i]);
  47418. }
  47419. return shapeUV;
  47420. };
  47421. // adds a new particle object in the particles array
  47422. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47423. if (bInfo === void 0) { bInfo = null; }
  47424. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47425. this.particles.push(sp);
  47426. return sp;
  47427. };
  47428. /**
  47429. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47430. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47431. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47432. * `nb` (positive integer) the number of particles to be created from this model
  47433. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47434. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47435. */
  47436. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47437. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47438. var meshInd = mesh.getIndices();
  47439. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47440. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47441. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47442. var bbInfo;
  47443. if (this._particlesIntersect) {
  47444. bbInfo = mesh.getBoundingInfo();
  47445. }
  47446. var shape = this._posToShape(meshPos);
  47447. var shapeUV = this._uvsToShapeUV(meshUV);
  47448. var posfunc = options ? options.positionFunction : null;
  47449. var vtxfunc = options ? options.vertexFunction : null;
  47450. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47451. // particles
  47452. var sp;
  47453. var currentCopy;
  47454. var idx = this.nbParticles;
  47455. for (var i = 0; i < nb; i++) {
  47456. var currentPos = this._positions.length;
  47457. var currentInd = this._indices.length;
  47458. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47459. if (this._updatable) {
  47460. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47461. sp.position.copyFrom(currentCopy.position);
  47462. sp.rotation.copyFrom(currentCopy.rotation);
  47463. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47464. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47465. }
  47466. if (currentCopy.color && sp.color) {
  47467. sp.color.copyFrom(currentCopy.color);
  47468. }
  47469. sp.scaling.copyFrom(currentCopy.scaling);
  47470. sp.uvs.copyFrom(currentCopy.uvs);
  47471. }
  47472. this._index += shape.length;
  47473. idx++;
  47474. }
  47475. this.nbParticles += nb;
  47476. this._shapeCounter++;
  47477. return this._shapeCounter - 1;
  47478. };
  47479. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47480. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47481. this._resetCopy();
  47482. if (particle._model._positionFunction) {
  47483. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47484. }
  47485. if (this._copy.rotationQuaternion) {
  47486. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47487. }
  47488. else {
  47489. this._yaw = this._copy.rotation.y;
  47490. this._pitch = this._copy.rotation.x;
  47491. this._roll = this._copy.rotation.z;
  47492. this._quaternionRotationYPR();
  47493. }
  47494. this._quaternionToRotationMatrix();
  47495. this._shape = particle._model._shape;
  47496. for (var pt = 0; pt < this._shape.length; pt++) {
  47497. this._vertex.x = this._shape[pt].x;
  47498. this._vertex.y = this._shape[pt].y;
  47499. this._vertex.z = this._shape[pt].z;
  47500. if (particle._model._vertexFunction) {
  47501. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47502. }
  47503. this._vertex.x *= this._copy.scaling.x;
  47504. this._vertex.y *= this._copy.scaling.y;
  47505. this._vertex.z *= this._copy.scaling.z;
  47506. this._vertex.x += this._copy.pivot.x;
  47507. this._vertex.y += this._copy.pivot.y;
  47508. this._vertex.z += this._copy.pivot.z;
  47509. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47510. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47511. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47512. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47513. }
  47514. particle.position.x = 0.0;
  47515. particle.position.y = 0.0;
  47516. particle.position.z = 0.0;
  47517. particle.rotation.x = 0.0;
  47518. particle.rotation.y = 0.0;
  47519. particle.rotation.z = 0.0;
  47520. particle.rotationQuaternion = null;
  47521. particle.scaling.x = 1.0;
  47522. particle.scaling.y = 1.0;
  47523. particle.scaling.z = 1.0;
  47524. };
  47525. /**
  47526. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47527. * Returns the SPS.
  47528. */
  47529. SolidParticleSystem.prototype.rebuildMesh = function () {
  47530. for (var p = 0; p < this.particles.length; p++) {
  47531. this._rebuildParticle(this.particles[p]);
  47532. }
  47533. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47534. return this;
  47535. };
  47536. /**
  47537. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47538. * This method calls `updateParticle()` for each particle of the SPS.
  47539. * For an animated SPS, it is usually called within the render loop.
  47540. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47541. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47542. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47543. * Returns the SPS.
  47544. */
  47545. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47546. if (start === void 0) { start = 0; }
  47547. if (end === void 0) { end = this.nbParticles - 1; }
  47548. if (update === void 0) { update = true; }
  47549. if (!this._updatable) {
  47550. return this;
  47551. }
  47552. // custom beforeUpdate
  47553. this.beforeUpdateParticles(start, end, update);
  47554. this._cam_axisX.x = 1.0;
  47555. this._cam_axisX.y = 0.0;
  47556. this._cam_axisX.z = 0.0;
  47557. this._cam_axisY.x = 0.0;
  47558. this._cam_axisY.y = 1.0;
  47559. this._cam_axisY.z = 0.0;
  47560. this._cam_axisZ.x = 0.0;
  47561. this._cam_axisZ.y = 0.0;
  47562. this._cam_axisZ.z = 1.0;
  47563. // cases when the World Matrix is to be computed first
  47564. if (this.billboard || this._depthSort) {
  47565. this.mesh.computeWorldMatrix(true);
  47566. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47567. }
  47568. // if the particles will always face the camera
  47569. if (this.billboard) {
  47570. // compute the camera position and un-rotate it by the current mesh rotation
  47571. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47572. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47573. this._cam_axisZ.normalize();
  47574. // same for camera up vector extracted from the cam view matrix
  47575. var view = this._camera.getViewMatrix(true);
  47576. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47577. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47578. this._cam_axisY.normalize();
  47579. this._cam_axisX.normalize();
  47580. }
  47581. // if depthSort, compute the camera global position in the mesh local system
  47582. if (this._depthSort) {
  47583. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47584. }
  47585. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47586. var idx = 0; // current position index in the global array positions32
  47587. var index = 0; // position start index in the global array positions32 of the current particle
  47588. var colidx = 0; // current color index in the global array colors32
  47589. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47590. var uvidx = 0; // current uv index in the global array uvs32
  47591. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47592. var pt = 0; // current index in the particle model shape
  47593. if (this.mesh.isFacetDataEnabled) {
  47594. this._computeBoundingBox = true;
  47595. }
  47596. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47597. if (this._computeBoundingBox) {
  47598. if (start == 0 && end == this.nbParticles - 1) {
  47599. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47600. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47601. }
  47602. else {
  47603. if (this.mesh._boundingInfo) {
  47604. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47605. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47606. }
  47607. }
  47608. }
  47609. // particle loop
  47610. index = this.particles[start]._pos;
  47611. var vpos = (index / 3) | 0;
  47612. colorIndex = vpos * 4;
  47613. uvIndex = vpos * 2;
  47614. for (var p = start; p <= end; p++) {
  47615. this._particle = this.particles[p];
  47616. this._shape = this._particle._model._shape;
  47617. this._shapeUV = this._particle._model._shapeUV;
  47618. // call to custom user function to update the particle properties
  47619. this.updateParticle(this._particle);
  47620. // camera-particle distance for depth sorting
  47621. if (this._depthSort && this._depthSortParticles) {
  47622. var dsp = this.depthSortedParticles[p];
  47623. dsp.ind = this._particle._ind;
  47624. dsp.indicesLength = this._particle._model._indicesLength;
  47625. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47626. }
  47627. // skip the computations for inactive or already invisible particles
  47628. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47629. // increment indexes for the next particle
  47630. pt = this._shape.length;
  47631. index += pt * 3;
  47632. colorIndex += pt * 4;
  47633. uvIndex += pt * 2;
  47634. continue;
  47635. }
  47636. if (this._particle.isVisible) {
  47637. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47638. // particle rotation matrix
  47639. if (this.billboard) {
  47640. this._particle.rotation.x = 0.0;
  47641. this._particle.rotation.y = 0.0;
  47642. }
  47643. if (this._computeParticleRotation || this.billboard) {
  47644. if (this._particle.rotationQuaternion) {
  47645. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47646. }
  47647. else {
  47648. this._yaw = this._particle.rotation.y;
  47649. this._pitch = this._particle.rotation.x;
  47650. this._roll = this._particle.rotation.z;
  47651. this._quaternionRotationYPR();
  47652. }
  47653. this._quaternionToRotationMatrix();
  47654. }
  47655. // particle vertex loop
  47656. for (pt = 0; pt < this._shape.length; pt++) {
  47657. idx = index + pt * 3;
  47658. colidx = colorIndex + pt * 4;
  47659. uvidx = uvIndex + pt * 2;
  47660. this._vertex.x = this._shape[pt].x;
  47661. this._vertex.y = this._shape[pt].y;
  47662. this._vertex.z = this._shape[pt].z;
  47663. if (this._computeParticleVertex) {
  47664. this.updateParticleVertex(this._particle, this._vertex, pt);
  47665. }
  47666. // positions
  47667. this._vertex.x *= this._particle.scaling.x;
  47668. this._vertex.y *= this._particle.scaling.y;
  47669. this._vertex.z *= this._particle.scaling.z;
  47670. this._vertex.x += this._particle.pivot.x;
  47671. this._vertex.y += this._particle.pivot.y;
  47672. this._vertex.z += this._particle.pivot.z;
  47673. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47674. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47675. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47676. 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;
  47677. 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;
  47678. 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;
  47679. if (this._computeBoundingBox) {
  47680. if (this._positions32[idx] < this._minimum.x) {
  47681. this._minimum.x = this._positions32[idx];
  47682. }
  47683. if (this._positions32[idx] > this._maximum.x) {
  47684. this._maximum.x = this._positions32[idx];
  47685. }
  47686. if (this._positions32[idx + 1] < this._minimum.y) {
  47687. this._minimum.y = this._positions32[idx + 1];
  47688. }
  47689. if (this._positions32[idx + 1] > this._maximum.y) {
  47690. this._maximum.y = this._positions32[idx + 1];
  47691. }
  47692. if (this._positions32[idx + 2] < this._minimum.z) {
  47693. this._minimum.z = this._positions32[idx + 2];
  47694. }
  47695. if (this._positions32[idx + 2] > this._maximum.z) {
  47696. this._maximum.z = this._positions32[idx + 2];
  47697. }
  47698. }
  47699. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47700. if (!this._computeParticleVertex) {
  47701. this._normal.x = this._fixedNormal32[idx];
  47702. this._normal.y = this._fixedNormal32[idx + 1];
  47703. this._normal.z = this._fixedNormal32[idx + 2];
  47704. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47705. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47706. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47707. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47708. 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;
  47709. 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;
  47710. }
  47711. if (this._computeParticleColor && this._particle.color) {
  47712. this._colors32[colidx] = this._particle.color.r;
  47713. this._colors32[colidx + 1] = this._particle.color.g;
  47714. this._colors32[colidx + 2] = this._particle.color.b;
  47715. this._colors32[colidx + 3] = this._particle.color.a;
  47716. }
  47717. if (this._computeParticleTexture) {
  47718. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47719. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47720. }
  47721. }
  47722. }
  47723. else {
  47724. this._particle._stillInvisible = true; // mark the particle as invisible
  47725. for (pt = 0; pt < this._shape.length; pt++) {
  47726. idx = index + pt * 3;
  47727. colidx = colorIndex + pt * 4;
  47728. uvidx = uvIndex + pt * 2;
  47729. this._positions32[idx] = 0.0;
  47730. this._positions32[idx + 1] = 0.0;
  47731. this._positions32[idx + 2] = 0.0;
  47732. this._normals32[idx] = 0.0;
  47733. this._normals32[idx + 1] = 0.0;
  47734. this._normals32[idx + 2] = 0.0;
  47735. if (this._computeParticleColor && this._particle.color) {
  47736. this._colors32[colidx] = this._particle.color.r;
  47737. this._colors32[colidx + 1] = this._particle.color.g;
  47738. this._colors32[colidx + 2] = this._particle.color.b;
  47739. this._colors32[colidx + 3] = this._particle.color.a;
  47740. }
  47741. if (this._computeParticleTexture) {
  47742. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47743. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47744. }
  47745. }
  47746. }
  47747. // if the particle intersections must be computed : update the bbInfo
  47748. if (this._particlesIntersect) {
  47749. var bInfo = this._particle._boundingInfo;
  47750. var bBox = bInfo.boundingBox;
  47751. var bSphere = bInfo.boundingSphere;
  47752. if (!this._bSphereOnly) {
  47753. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47754. for (var b = 0; b < bBox.vectors.length; b++) {
  47755. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47756. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47757. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47758. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47759. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47760. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47761. 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;
  47762. 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;
  47763. 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;
  47764. }
  47765. bBox._update(this.mesh._worldMatrix);
  47766. }
  47767. // place and scale the particle bouding sphere in the SPS local system, then update it
  47768. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47769. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47770. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47771. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47772. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47773. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47774. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47775. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47776. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47777. 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));
  47778. bSphere._update(this.mesh._worldMatrix);
  47779. }
  47780. // increment indexes for the next particle
  47781. index = idx + 3;
  47782. colorIndex = colidx + 4;
  47783. uvIndex = uvidx + 2;
  47784. }
  47785. // if the VBO must be updated
  47786. if (update) {
  47787. if (this._computeParticleColor) {
  47788. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47789. }
  47790. if (this._computeParticleTexture) {
  47791. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47792. }
  47793. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47794. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47795. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47796. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47797. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47798. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47799. for (var i = 0; i < this._normals32.length; i++) {
  47800. this._fixedNormal32[i] = this._normals32[i];
  47801. }
  47802. }
  47803. if (!this.mesh.areNormalsFrozen) {
  47804. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47805. }
  47806. }
  47807. if (this._depthSort && this._depthSortParticles) {
  47808. this.depthSortedParticles.sort(this._depthSortFunction);
  47809. var dspl = this.depthSortedParticles.length;
  47810. var sorted = 0;
  47811. var lind = 0;
  47812. var sind = 0;
  47813. var sid = 0;
  47814. for (sorted = 0; sorted < dspl; sorted++) {
  47815. lind = this.depthSortedParticles[sorted].indicesLength;
  47816. sind = this.depthSortedParticles[sorted].ind;
  47817. for (var i = 0; i < lind; i++) {
  47818. this._indices32[sid] = this._indices[sind + i];
  47819. sid++;
  47820. }
  47821. }
  47822. this.mesh.updateIndices(this._indices32);
  47823. }
  47824. }
  47825. if (this._computeBoundingBox) {
  47826. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47827. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47828. }
  47829. this.afterUpdateParticles(start, end, update);
  47830. return this;
  47831. };
  47832. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47833. this._halfroll = this._roll * 0.5;
  47834. this._halfpitch = this._pitch * 0.5;
  47835. this._halfyaw = this._yaw * 0.5;
  47836. this._sinRoll = Math.sin(this._halfroll);
  47837. this._cosRoll = Math.cos(this._halfroll);
  47838. this._sinPitch = Math.sin(this._halfpitch);
  47839. this._cosPitch = Math.cos(this._halfpitch);
  47840. this._sinYaw = Math.sin(this._halfyaw);
  47841. this._cosYaw = Math.cos(this._halfyaw);
  47842. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47843. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47844. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47845. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47846. };
  47847. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47848. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47849. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47850. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47851. this._rotMatrix.m[3] = 0;
  47852. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47853. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47854. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47855. this._rotMatrix.m[7] = 0;
  47856. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47857. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47858. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47859. this._rotMatrix.m[11] = 0;
  47860. this._rotMatrix.m[12] = 0;
  47861. this._rotMatrix.m[13] = 0;
  47862. this._rotMatrix.m[14] = 0;
  47863. this._rotMatrix.m[15] = 1.0;
  47864. };
  47865. /**
  47866. * Disposes the SPS.
  47867. * Returns nothing.
  47868. */
  47869. SolidParticleSystem.prototype.dispose = function () {
  47870. this.mesh.dispose();
  47871. this.vars = null;
  47872. // drop references to internal big arrays for the GC
  47873. this._positions = null;
  47874. this._indices = null;
  47875. this._normals = null;
  47876. this._uvs = null;
  47877. this._colors = null;
  47878. this._indices32 = null;
  47879. this._positions32 = null;
  47880. this._normals32 = null;
  47881. this._fixedNormal32 = null;
  47882. this._uvs32 = null;
  47883. this._colors32 = null;
  47884. this.pickedParticles = null;
  47885. };
  47886. /**
  47887. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47889. * Returns the SPS.
  47890. */
  47891. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47892. if (!this._isVisibilityBoxLocked) {
  47893. this.mesh.refreshBoundingInfo();
  47894. }
  47895. return this;
  47896. };
  47897. /**
  47898. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47899. * @param size the size (float) of the visibility box
  47900. * note : this doesn't lock the SPS mesh bounding box.
  47901. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47902. */
  47903. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47904. var vis = size / 2;
  47905. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47906. };
  47907. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47908. // getter and setter
  47909. get: function () {
  47910. return this._alwaysVisible;
  47911. },
  47912. /**
  47913. * Sets the SPS as always visible or not
  47914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47915. */
  47916. set: function (val) {
  47917. this._alwaysVisible = val;
  47918. this.mesh.alwaysSelectAsActiveMesh = val;
  47919. },
  47920. enumerable: true,
  47921. configurable: true
  47922. });
  47923. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47924. get: function () {
  47925. return this._isVisibilityBoxLocked;
  47926. },
  47927. /**
  47928. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47930. */
  47931. set: function (val) {
  47932. this._isVisibilityBoxLocked = val;
  47933. var boundingInfo = this.mesh.getBoundingInfo();
  47934. boundingInfo.isLocked = val;
  47935. },
  47936. enumerable: true,
  47937. configurable: true
  47938. });
  47939. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47940. // getters
  47941. get: function () {
  47942. return this._computeParticleRotation;
  47943. },
  47944. // Optimizer setters
  47945. /**
  47946. * Tells to `setParticles()` to compute the particle rotations or not.
  47947. * Default value : true. The SPS is faster when it's set to false.
  47948. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47949. */
  47950. set: function (val) {
  47951. this._computeParticleRotation = val;
  47952. },
  47953. enumerable: true,
  47954. configurable: true
  47955. });
  47956. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47957. get: function () {
  47958. return this._computeParticleColor;
  47959. },
  47960. /**
  47961. * Tells to `setParticles()` to compute the particle colors or not.
  47962. * Default value : true. The SPS is faster when it's set to false.
  47963. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47964. */
  47965. set: function (val) {
  47966. this._computeParticleColor = val;
  47967. },
  47968. enumerable: true,
  47969. configurable: true
  47970. });
  47971. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47972. get: function () {
  47973. return this._computeParticleTexture;
  47974. },
  47975. /**
  47976. * Tells to `setParticles()` to compute the particle textures or not.
  47977. * Default value : true. The SPS is faster when it's set to false.
  47978. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47979. */
  47980. set: function (val) {
  47981. this._computeParticleTexture = val;
  47982. },
  47983. enumerable: true,
  47984. configurable: true
  47985. });
  47986. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47987. get: function () {
  47988. return this._computeParticleVertex;
  47989. },
  47990. /**
  47991. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47992. * Default value : false. The SPS is faster when it's set to false.
  47993. * Note : the particle custom vertex positions aren't stored values.
  47994. */
  47995. set: function (val) {
  47996. this._computeParticleVertex = val;
  47997. },
  47998. enumerable: true,
  47999. configurable: true
  48000. });
  48001. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48002. get: function () {
  48003. return this._computeBoundingBox;
  48004. },
  48005. /**
  48006. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48007. */
  48008. set: function (val) {
  48009. this._computeBoundingBox = val;
  48010. },
  48011. enumerable: true,
  48012. configurable: true
  48013. });
  48014. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48015. get: function () {
  48016. return this._depthSortParticles;
  48017. },
  48018. /**
  48019. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48020. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48021. * Default : `true`
  48022. */
  48023. set: function (val) {
  48024. this._depthSortParticles = val;
  48025. },
  48026. enumerable: true,
  48027. configurable: true
  48028. });
  48029. // =======================================================================
  48030. // Particle behavior logic
  48031. // these following methods may be overwritten by the user to fit his needs
  48032. /**
  48033. * This function does nothing. It may be overwritten to set all the particle first values.
  48034. * The SPS doesn't call this function, you may have to call it by your own.
  48035. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48036. */
  48037. SolidParticleSystem.prototype.initParticles = function () {
  48038. };
  48039. /**
  48040. * This function does nothing. It may be overwritten to recycle a particle.
  48041. * The SPS doesn't call this function, you may have to call it by your own.
  48042. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48043. */
  48044. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48045. return particle;
  48046. };
  48047. /**
  48048. * Updates a particle : this function should be overwritten by the user.
  48049. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48051. * ex : just set a particle position or velocity and recycle conditions
  48052. */
  48053. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48054. return particle;
  48055. };
  48056. /**
  48057. * Updates a vertex of a particle : it can be overwritten by the user.
  48058. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48059. * @param particle the current particle
  48060. * @param vertex the current index of the current particle
  48061. * @param pt the index of the current vertex in the particle shape
  48062. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48063. * ex : just set a vertex particle position
  48064. */
  48065. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48066. return vertex;
  48067. };
  48068. /**
  48069. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48070. * This does nothing and may be overwritten by the user.
  48071. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48072. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48073. * @param update the boolean update value actually passed to setParticles()
  48074. */
  48075. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48076. };
  48077. /**
  48078. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48079. * This will be passed three parameters.
  48080. * This does nothing and may be overwritten by the user.
  48081. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48082. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48083. * @param update the boolean update value actually passed to setParticles()
  48084. */
  48085. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48086. };
  48087. return SolidParticleSystem;
  48088. }());
  48089. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48090. })(BABYLON || (BABYLON = {}));
  48091. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48092. var BABYLON;
  48093. (function (BABYLON) {
  48094. var ShaderMaterial = /** @class */ (function (_super) {
  48095. __extends(ShaderMaterial, _super);
  48096. function ShaderMaterial(name, scene, shaderPath, options) {
  48097. var _this = _super.call(this, name, scene) || this;
  48098. _this._textures = {};
  48099. _this._textureArrays = {};
  48100. _this._floats = {};
  48101. _this._ints = {};
  48102. _this._floatsArrays = {};
  48103. _this._colors3 = {};
  48104. _this._colors3Arrays = {};
  48105. _this._colors4 = {};
  48106. _this._vectors2 = {};
  48107. _this._vectors3 = {};
  48108. _this._vectors4 = {};
  48109. _this._matrices = {};
  48110. _this._matrices3x3 = {};
  48111. _this._matrices2x2 = {};
  48112. _this._vectors2Arrays = {};
  48113. _this._vectors3Arrays = {};
  48114. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48115. _this._shaderPath = shaderPath;
  48116. options.needAlphaBlending = options.needAlphaBlending || false;
  48117. options.needAlphaTesting = options.needAlphaTesting || false;
  48118. options.attributes = options.attributes || ["position", "normal", "uv"];
  48119. options.uniforms = options.uniforms || ["worldViewProjection"];
  48120. options.uniformBuffers = options.uniformBuffers || [];
  48121. options.samplers = options.samplers || [];
  48122. options.defines = options.defines || [];
  48123. _this._options = options;
  48124. return _this;
  48125. }
  48126. ShaderMaterial.prototype.getClassName = function () {
  48127. return "ShaderMaterial";
  48128. };
  48129. ShaderMaterial.prototype.needAlphaBlending = function () {
  48130. return this._options.needAlphaBlending;
  48131. };
  48132. ShaderMaterial.prototype.needAlphaTesting = function () {
  48133. return this._options.needAlphaTesting;
  48134. };
  48135. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48136. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48137. this._options.uniforms.push(uniformName);
  48138. }
  48139. };
  48140. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48141. if (this._options.samplers.indexOf(name) === -1) {
  48142. this._options.samplers.push(name);
  48143. }
  48144. this._textures[name] = texture;
  48145. return this;
  48146. };
  48147. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48148. if (this._options.samplers.indexOf(name) === -1) {
  48149. this._options.samplers.push(name);
  48150. }
  48151. this._checkUniform(name);
  48152. this._textureArrays[name] = textures;
  48153. return this;
  48154. };
  48155. ShaderMaterial.prototype.setFloat = function (name, value) {
  48156. this._checkUniform(name);
  48157. this._floats[name] = value;
  48158. return this;
  48159. };
  48160. ShaderMaterial.prototype.setInt = function (name, value) {
  48161. this._checkUniform(name);
  48162. this._ints[name] = value;
  48163. return this;
  48164. };
  48165. ShaderMaterial.prototype.setFloats = function (name, value) {
  48166. this._checkUniform(name);
  48167. this._floatsArrays[name] = value;
  48168. return this;
  48169. };
  48170. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48171. this._checkUniform(name);
  48172. this._colors3[name] = value;
  48173. return this;
  48174. };
  48175. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48176. this._checkUniform(name);
  48177. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48178. color.toArray(arr, arr.length);
  48179. return arr;
  48180. }, []);
  48181. return this;
  48182. };
  48183. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48184. this._checkUniform(name);
  48185. this._colors4[name] = value;
  48186. return this;
  48187. };
  48188. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48189. this._checkUniform(name);
  48190. this._vectors2[name] = value;
  48191. return this;
  48192. };
  48193. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48194. this._checkUniform(name);
  48195. this._vectors3[name] = value;
  48196. return this;
  48197. };
  48198. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48199. this._checkUniform(name);
  48200. this._vectors4[name] = value;
  48201. return this;
  48202. };
  48203. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48204. this._checkUniform(name);
  48205. this._matrices[name] = value;
  48206. return this;
  48207. };
  48208. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48209. this._checkUniform(name);
  48210. this._matrices3x3[name] = value;
  48211. return this;
  48212. };
  48213. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48214. this._checkUniform(name);
  48215. this._matrices2x2[name] = value;
  48216. return this;
  48217. };
  48218. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48219. this._checkUniform(name);
  48220. this._vectors2Arrays[name] = value;
  48221. return this;
  48222. };
  48223. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48224. this._checkUniform(name);
  48225. this._vectors3Arrays[name] = value;
  48226. return this;
  48227. };
  48228. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48229. if (!mesh) {
  48230. return true;
  48231. }
  48232. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48233. return false;
  48234. }
  48235. return false;
  48236. };
  48237. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48238. var scene = this.getScene();
  48239. var engine = scene.getEngine();
  48240. if (!this.checkReadyOnEveryCall) {
  48241. if (this._renderId === scene.getRenderId()) {
  48242. if (this._checkCache(scene, mesh, useInstances)) {
  48243. return true;
  48244. }
  48245. }
  48246. }
  48247. // Instances
  48248. var defines = [];
  48249. var attribs = [];
  48250. var fallbacks = new BABYLON.EffectFallbacks();
  48251. if (useInstances) {
  48252. defines.push("#define INSTANCES");
  48253. }
  48254. for (var index = 0; index < this._options.defines.length; index++) {
  48255. defines.push(this._options.defines[index]);
  48256. }
  48257. for (var index = 0; index < this._options.attributes.length; index++) {
  48258. attribs.push(this._options.attributes[index]);
  48259. }
  48260. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48261. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48262. defines.push("#define VERTEXCOLOR");
  48263. }
  48264. // Bones
  48265. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48268. if (mesh.numBoneInfluencers > 4) {
  48269. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48270. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48271. }
  48272. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48273. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48274. fallbacks.addCPUSkinningFallback(0, mesh);
  48275. if (this._options.uniforms.indexOf("mBones") === -1) {
  48276. this._options.uniforms.push("mBones");
  48277. }
  48278. }
  48279. else {
  48280. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48281. }
  48282. // Textures
  48283. for (var name in this._textures) {
  48284. if (!this._textures[name].isReady()) {
  48285. return false;
  48286. }
  48287. }
  48288. // Alpha test
  48289. if (engine.getAlphaTesting()) {
  48290. defines.push("#define ALPHATEST");
  48291. }
  48292. var previousEffect = this._effect;
  48293. var join = defines.join("\n");
  48294. this._effect = engine.createEffect(this._shaderPath, {
  48295. attributes: attribs,
  48296. uniformsNames: this._options.uniforms,
  48297. uniformBuffersNames: this._options.uniformBuffers,
  48298. samplers: this._options.samplers,
  48299. defines: join,
  48300. fallbacks: fallbacks,
  48301. onCompiled: this.onCompiled,
  48302. onError: this.onError
  48303. }, engine);
  48304. if (!this._effect.isReady()) {
  48305. return false;
  48306. }
  48307. if (previousEffect !== this._effect) {
  48308. scene.resetCachedMaterial();
  48309. }
  48310. this._renderId = scene.getRenderId();
  48311. return true;
  48312. };
  48313. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48314. var scene = this.getScene();
  48315. if (!this._effect) {
  48316. return;
  48317. }
  48318. if (this._options.uniforms.indexOf("world") !== -1) {
  48319. this._effect.setMatrix("world", world);
  48320. }
  48321. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48322. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48323. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48324. }
  48325. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48326. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48327. }
  48328. };
  48329. ShaderMaterial.prototype.bind = function (world, mesh) {
  48330. // Std values
  48331. this.bindOnlyWorldMatrix(world);
  48332. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48333. if (this._options.uniforms.indexOf("view") !== -1) {
  48334. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48335. }
  48336. if (this._options.uniforms.indexOf("projection") !== -1) {
  48337. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48338. }
  48339. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48340. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48341. }
  48342. // Bones
  48343. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48344. var name;
  48345. // Texture
  48346. for (name in this._textures) {
  48347. this._effect.setTexture(name, this._textures[name]);
  48348. }
  48349. // Texture arrays
  48350. for (name in this._textureArrays) {
  48351. this._effect.setTextureArray(name, this._textureArrays[name]);
  48352. }
  48353. // Int
  48354. for (name in this._ints) {
  48355. this._effect.setInt(name, this._ints[name]);
  48356. }
  48357. // Float
  48358. for (name in this._floats) {
  48359. this._effect.setFloat(name, this._floats[name]);
  48360. }
  48361. // Floats
  48362. for (name in this._floatsArrays) {
  48363. this._effect.setArray(name, this._floatsArrays[name]);
  48364. }
  48365. // Color3
  48366. for (name in this._colors3) {
  48367. this._effect.setColor3(name, this._colors3[name]);
  48368. }
  48369. for (name in this._colors3Arrays) {
  48370. this._effect.setArray3(name, this._colors3Arrays[name]);
  48371. }
  48372. // Color4
  48373. for (name in this._colors4) {
  48374. var color = this._colors4[name];
  48375. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48376. }
  48377. // Vector2
  48378. for (name in this._vectors2) {
  48379. this._effect.setVector2(name, this._vectors2[name]);
  48380. }
  48381. // Vector3
  48382. for (name in this._vectors3) {
  48383. this._effect.setVector3(name, this._vectors3[name]);
  48384. }
  48385. // Vector4
  48386. for (name in this._vectors4) {
  48387. this._effect.setVector4(name, this._vectors4[name]);
  48388. }
  48389. // Matrix
  48390. for (name in this._matrices) {
  48391. this._effect.setMatrix(name, this._matrices[name]);
  48392. }
  48393. // Matrix 3x3
  48394. for (name in this._matrices3x3) {
  48395. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48396. }
  48397. // Matrix 2x2
  48398. for (name in this._matrices2x2) {
  48399. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48400. }
  48401. // Vector2Array
  48402. for (name in this._vectors2Arrays) {
  48403. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48404. }
  48405. // Vector3Array
  48406. for (name in this._vectors3Arrays) {
  48407. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48408. }
  48409. }
  48410. this._afterBind(mesh);
  48411. };
  48412. ShaderMaterial.prototype.getActiveTextures = function () {
  48413. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48414. for (var name in this._textures) {
  48415. activeTextures.push(this._textures[name]);
  48416. }
  48417. for (var name in this._textureArrays) {
  48418. var array = this._textureArrays[name];
  48419. for (var index = 0; index < array.length; index++) {
  48420. activeTextures.push(array[index]);
  48421. }
  48422. }
  48423. return activeTextures;
  48424. };
  48425. ShaderMaterial.prototype.hasTexture = function (texture) {
  48426. if (_super.prototype.hasTexture.call(this, texture)) {
  48427. return true;
  48428. }
  48429. for (var name in this._textures) {
  48430. if (this._textures[name] === texture) {
  48431. return true;
  48432. }
  48433. }
  48434. for (var name in this._textureArrays) {
  48435. var array = this._textureArrays[name];
  48436. for (var index = 0; index < array.length; index++) {
  48437. if (array[index] === texture) {
  48438. return true;
  48439. }
  48440. }
  48441. }
  48442. return false;
  48443. };
  48444. ShaderMaterial.prototype.clone = function (name) {
  48445. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48446. return newShaderMaterial;
  48447. };
  48448. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48449. if (forceDisposeTextures) {
  48450. var name;
  48451. for (name in this._textures) {
  48452. this._textures[name].dispose();
  48453. }
  48454. for (name in this._textureArrays) {
  48455. var array = this._textureArrays[name];
  48456. for (var index = 0; index < array.length; index++) {
  48457. array[index].dispose();
  48458. }
  48459. }
  48460. }
  48461. this._textures = {};
  48462. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48463. };
  48464. ShaderMaterial.prototype.serialize = function () {
  48465. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48466. serializationObject.customType = "BABYLON.ShaderMaterial";
  48467. serializationObject.options = this._options;
  48468. serializationObject.shaderPath = this._shaderPath;
  48469. var name;
  48470. // Texture
  48471. serializationObject.textures = {};
  48472. for (name in this._textures) {
  48473. serializationObject.textures[name] = this._textures[name].serialize();
  48474. }
  48475. // Texture arrays
  48476. serializationObject.textureArrays = {};
  48477. for (name in this._textureArrays) {
  48478. serializationObject.textureArrays[name] = [];
  48479. var array = this._textureArrays[name];
  48480. for (var index = 0; index < array.length; index++) {
  48481. serializationObject.textureArrays[name].push(array[index].serialize());
  48482. }
  48483. }
  48484. // Float
  48485. serializationObject.floats = {};
  48486. for (name in this._floats) {
  48487. serializationObject.floats[name] = this._floats[name];
  48488. }
  48489. // Float s
  48490. serializationObject.FloatArrays = {};
  48491. for (name in this._floatsArrays) {
  48492. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48493. }
  48494. // Color3
  48495. serializationObject.colors3 = {};
  48496. for (name in this._colors3) {
  48497. serializationObject.colors3[name] = this._colors3[name].asArray();
  48498. }
  48499. // Color3 array
  48500. serializationObject.colors3Arrays = {};
  48501. for (name in this._colors3Arrays) {
  48502. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48503. }
  48504. // Color4
  48505. serializationObject.colors4 = {};
  48506. for (name in this._colors4) {
  48507. serializationObject.colors4[name] = this._colors4[name].asArray();
  48508. }
  48509. // Vector2
  48510. serializationObject.vectors2 = {};
  48511. for (name in this._vectors2) {
  48512. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48513. }
  48514. // Vector3
  48515. serializationObject.vectors3 = {};
  48516. for (name in this._vectors3) {
  48517. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48518. }
  48519. // Vector4
  48520. serializationObject.vectors4 = {};
  48521. for (name in this._vectors4) {
  48522. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48523. }
  48524. // Matrix
  48525. serializationObject.matrices = {};
  48526. for (name in this._matrices) {
  48527. serializationObject.matrices[name] = this._matrices[name].asArray();
  48528. }
  48529. // Matrix 3x3
  48530. serializationObject.matrices3x3 = {};
  48531. for (name in this._matrices3x3) {
  48532. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48533. }
  48534. // Matrix 2x2
  48535. serializationObject.matrices2x2 = {};
  48536. for (name in this._matrices2x2) {
  48537. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48538. }
  48539. // Vector2Array
  48540. serializationObject.vectors2Arrays = {};
  48541. for (name in this._vectors2Arrays) {
  48542. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48543. }
  48544. // Vector3Array
  48545. serializationObject.vectors3Arrays = {};
  48546. for (name in this._vectors3Arrays) {
  48547. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48548. }
  48549. return serializationObject;
  48550. };
  48551. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48552. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48553. var name;
  48554. // Texture
  48555. for (name in source.textures) {
  48556. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48557. }
  48558. // Texture arrays
  48559. for (name in source.textureArrays) {
  48560. var array = source.textureArrays[name];
  48561. var textureArray = new Array();
  48562. for (var index = 0; index < array.length; index++) {
  48563. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48564. }
  48565. material.setTextureArray(name, textureArray);
  48566. }
  48567. // Float
  48568. for (name in source.floats) {
  48569. material.setFloat(name, source.floats[name]);
  48570. }
  48571. // Float s
  48572. for (name in source.floatsArrays) {
  48573. material.setFloats(name, source.floatsArrays[name]);
  48574. }
  48575. // Color3
  48576. for (name in source.colors3) {
  48577. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48578. }
  48579. // Color3 arrays
  48580. for (name in source.colors3Arrays) {
  48581. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48582. if (i % 3 === 0) {
  48583. arr.push([num]);
  48584. }
  48585. else {
  48586. arr[arr.length - 1].push(num);
  48587. }
  48588. return arr;
  48589. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48590. material.setColor3Array(name, colors);
  48591. }
  48592. // Color4
  48593. for (name in source.colors4) {
  48594. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48595. }
  48596. // Vector2
  48597. for (name in source.vectors2) {
  48598. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48599. }
  48600. // Vector3
  48601. for (name in source.vectors3) {
  48602. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48603. }
  48604. // Vector4
  48605. for (name in source.vectors4) {
  48606. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48607. }
  48608. // Matrix
  48609. for (name in source.matrices) {
  48610. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48611. }
  48612. // Matrix 3x3
  48613. for (name in source.matrices3x3) {
  48614. material.setMatrix3x3(name, source.matrices3x3[name]);
  48615. }
  48616. // Matrix 2x2
  48617. for (name in source.matrices2x2) {
  48618. material.setMatrix2x2(name, source.matrices2x2[name]);
  48619. }
  48620. // Vector2Array
  48621. for (name in source.vectors2Arrays) {
  48622. material.setArray2(name, source.vectors2Arrays[name]);
  48623. }
  48624. // Vector3Array
  48625. for (name in source.vectors3Arrays) {
  48626. material.setArray3(name, source.vectors3Arrays[name]);
  48627. }
  48628. return material;
  48629. };
  48630. return ShaderMaterial;
  48631. }(BABYLON.Material));
  48632. BABYLON.ShaderMaterial = ShaderMaterial;
  48633. })(BABYLON || (BABYLON = {}));
  48634. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48635. var BABYLON;
  48636. (function (BABYLON) {
  48637. var GroundMesh = /** @class */ (function (_super) {
  48638. __extends(GroundMesh, _super);
  48639. function GroundMesh(name, scene) {
  48640. var _this = _super.call(this, name, scene) || this;
  48641. _this.generateOctree = false;
  48642. return _this;
  48643. }
  48644. GroundMesh.prototype.getClassName = function () {
  48645. return "GroundMesh";
  48646. };
  48647. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48648. get: function () {
  48649. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48650. },
  48651. enumerable: true,
  48652. configurable: true
  48653. });
  48654. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48655. get: function () {
  48656. return this._subdivisionsX;
  48657. },
  48658. enumerable: true,
  48659. configurable: true
  48660. });
  48661. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48662. get: function () {
  48663. return this._subdivisionsY;
  48664. },
  48665. enumerable: true,
  48666. configurable: true
  48667. });
  48668. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48669. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48670. this._subdivisionsX = chunksCount;
  48671. this._subdivisionsY = chunksCount;
  48672. this.subdivide(chunksCount);
  48673. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48674. };
  48675. /**
  48676. * Returns a height (y) value in the Worl system :
  48677. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48678. * Returns the ground y position if (x, z) are outside the ground surface.
  48679. */
  48680. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48681. var world = this.getWorldMatrix();
  48682. var invMat = BABYLON.Tmp.Matrix[5];
  48683. world.invertToRef(invMat);
  48684. var tmpVect = BABYLON.Tmp.Vector3[8];
  48685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48686. x = tmpVect.x;
  48687. z = tmpVect.z;
  48688. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48689. return this.position.y;
  48690. }
  48691. if (!this._heightQuads || this._heightQuads.length == 0) {
  48692. this._initHeightQuads();
  48693. this._computeHeightQuads();
  48694. }
  48695. var facet = this._getFacetAt(x, z);
  48696. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48697. // return y in the World system
  48698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48699. return tmpVect.y;
  48700. };
  48701. /**
  48702. * Returns a normalized vector (Vector3) orthogonal to the ground
  48703. * at the ground coordinates (x, z) expressed in the World system.
  48704. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48705. */
  48706. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48707. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48708. this.getNormalAtCoordinatesToRef(x, z, normal);
  48709. return normal;
  48710. };
  48711. /**
  48712. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48713. * at the ground coordinates (x, z) expressed in the World system.
  48714. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48715. * Returns the GroundMesh.
  48716. */
  48717. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48718. var world = this.getWorldMatrix();
  48719. var tmpMat = BABYLON.Tmp.Matrix[5];
  48720. world.invertToRef(tmpMat);
  48721. var tmpVect = BABYLON.Tmp.Vector3[8];
  48722. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48723. x = tmpVect.x;
  48724. z = tmpVect.z;
  48725. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48726. return this;
  48727. }
  48728. if (!this._heightQuads || this._heightQuads.length == 0) {
  48729. this._initHeightQuads();
  48730. this._computeHeightQuads();
  48731. }
  48732. var facet = this._getFacetAt(x, z);
  48733. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48734. return this;
  48735. };
  48736. /**
  48737. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48738. * if the ground has been updated.
  48739. * This can be used in the render loop.
  48740. * Returns the GroundMesh.
  48741. */
  48742. GroundMesh.prototype.updateCoordinateHeights = function () {
  48743. if (!this._heightQuads || this._heightQuads.length == 0) {
  48744. this._initHeightQuads();
  48745. }
  48746. this._computeHeightQuads();
  48747. return this;
  48748. };
  48749. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48750. GroundMesh.prototype._getFacetAt = function (x, z) {
  48751. // retrieve col and row from x, z coordinates in the ground local system
  48752. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48753. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48754. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48755. var facet;
  48756. if (z < quad.slope.x * x + quad.slope.y) {
  48757. facet = quad.facet1;
  48758. }
  48759. else {
  48760. facet = quad.facet2;
  48761. }
  48762. return facet;
  48763. };
  48764. // Creates and populates the heightMap array with "facet" elements :
  48765. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48766. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48767. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48768. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48769. // Returns the GroundMesh.
  48770. GroundMesh.prototype._initHeightQuads = function () {
  48771. var subdivisionsX = this._subdivisionsX;
  48772. var subdivisionsY = this._subdivisionsY;
  48773. this._heightQuads = new Array();
  48774. for (var row = 0; row < subdivisionsY; row++) {
  48775. for (var col = 0; col < subdivisionsX; col++) {
  48776. 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) };
  48777. this._heightQuads[row * subdivisionsX + col] = quad;
  48778. }
  48779. }
  48780. return this;
  48781. };
  48782. // Compute each quad element values and update the the heightMap array :
  48783. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48784. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48785. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48786. // Returns the GroundMesh.
  48787. GroundMesh.prototype._computeHeightQuads = function () {
  48788. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48789. if (!positions) {
  48790. return this;
  48791. }
  48792. var v1 = BABYLON.Tmp.Vector3[3];
  48793. var v2 = BABYLON.Tmp.Vector3[2];
  48794. var v3 = BABYLON.Tmp.Vector3[1];
  48795. var v4 = BABYLON.Tmp.Vector3[0];
  48796. var v1v2 = BABYLON.Tmp.Vector3[4];
  48797. var v1v3 = BABYLON.Tmp.Vector3[5];
  48798. var v1v4 = BABYLON.Tmp.Vector3[6];
  48799. var norm1 = BABYLON.Tmp.Vector3[7];
  48800. var norm2 = BABYLON.Tmp.Vector3[8];
  48801. var i = 0;
  48802. var j = 0;
  48803. var k = 0;
  48804. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48805. var h = 0;
  48806. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48807. var d2 = 0;
  48808. var subdivisionsX = this._subdivisionsX;
  48809. var subdivisionsY = this._subdivisionsY;
  48810. for (var row = 0; row < subdivisionsY; row++) {
  48811. for (var col = 0; col < subdivisionsX; col++) {
  48812. i = col * 3;
  48813. j = row * (subdivisionsX + 1) * 3;
  48814. k = (row + 1) * (subdivisionsX + 1) * 3;
  48815. v1.x = positions[j + i];
  48816. v1.y = positions[j + i + 1];
  48817. v1.z = positions[j + i + 2];
  48818. v2.x = positions[j + i + 3];
  48819. v2.y = positions[j + i + 4];
  48820. v2.z = positions[j + i + 5];
  48821. v3.x = positions[k + i];
  48822. v3.y = positions[k + i + 1];
  48823. v3.z = positions[k + i + 2];
  48824. v4.x = positions[k + i + 3];
  48825. v4.y = positions[k + i + 4];
  48826. v4.z = positions[k + i + 5];
  48827. // 2D slope V1V4
  48828. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48829. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48830. // facet equations :
  48831. // we compute each facet normal vector
  48832. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48833. // we compute the value d by applying the equation to v1 which belongs to the plane
  48834. // then we store the facet equation in a Vector4
  48835. v2.subtractToRef(v1, v1v2);
  48836. v3.subtractToRef(v1, v1v3);
  48837. v4.subtractToRef(v1, v1v4);
  48838. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48839. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48840. norm1.normalize();
  48841. norm2.normalize();
  48842. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48843. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48844. var quad = this._heightQuads[row * subdivisionsX + col];
  48845. quad.slope.copyFromFloats(cd, h);
  48846. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48847. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48848. }
  48849. }
  48850. return this;
  48851. };
  48852. GroundMesh.prototype.serialize = function (serializationObject) {
  48853. _super.prototype.serialize.call(this, serializationObject);
  48854. serializationObject.subdivisionsX = this._subdivisionsX;
  48855. serializationObject.subdivisionsY = this._subdivisionsY;
  48856. serializationObject.minX = this._minX;
  48857. serializationObject.maxX = this._maxX;
  48858. serializationObject.minZ = this._minZ;
  48859. serializationObject.maxZ = this._maxZ;
  48860. serializationObject.width = this._width;
  48861. serializationObject.height = this._height;
  48862. };
  48863. GroundMesh.Parse = function (parsedMesh, scene) {
  48864. var result = new GroundMesh(parsedMesh.name, scene);
  48865. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48866. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48867. result._minX = parsedMesh.minX;
  48868. result._maxX = parsedMesh.maxX;
  48869. result._minZ = parsedMesh.minZ;
  48870. result._maxZ = parsedMesh.maxZ;
  48871. result._width = parsedMesh.width;
  48872. result._height = parsedMesh.height;
  48873. return result;
  48874. };
  48875. return GroundMesh;
  48876. }(BABYLON.Mesh));
  48877. BABYLON.GroundMesh = GroundMesh;
  48878. })(BABYLON || (BABYLON = {}));
  48879. //# sourceMappingURL=babylon.groundMesh.js.map
  48880. var BABYLON;
  48881. (function (BABYLON) {
  48882. /**
  48883. * Creates an instance based on a source mesh.
  48884. */
  48885. var InstancedMesh = /** @class */ (function (_super) {
  48886. __extends(InstancedMesh, _super);
  48887. function InstancedMesh(name, source) {
  48888. var _this = _super.call(this, name, source.getScene()) || this;
  48889. source.instances.push(_this);
  48890. _this._sourceMesh = source;
  48891. _this.position.copyFrom(source.position);
  48892. _this.rotation.copyFrom(source.rotation);
  48893. _this.scaling.copyFrom(source.scaling);
  48894. if (source.rotationQuaternion) {
  48895. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48896. }
  48897. _this.infiniteDistance = source.infiniteDistance;
  48898. _this.setPivotMatrix(source.getPivotMatrix());
  48899. _this.refreshBoundingInfo();
  48900. _this._syncSubMeshes();
  48901. return _this;
  48902. }
  48903. /**
  48904. * Returns the string "InstancedMesh".
  48905. */
  48906. InstancedMesh.prototype.getClassName = function () {
  48907. return "InstancedMesh";
  48908. };
  48909. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48910. // Methods
  48911. get: function () {
  48912. return this._sourceMesh.receiveShadows;
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. Object.defineProperty(InstancedMesh.prototype, "material", {
  48918. get: function () {
  48919. return this._sourceMesh.material;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48925. get: function () {
  48926. return this._sourceMesh.visibility;
  48927. },
  48928. enumerable: true,
  48929. configurable: true
  48930. });
  48931. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48932. get: function () {
  48933. return this._sourceMesh.skeleton;
  48934. },
  48935. enumerable: true,
  48936. configurable: true
  48937. });
  48938. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48939. get: function () {
  48940. return this._sourceMesh.renderingGroupId;
  48941. },
  48942. enumerable: true,
  48943. configurable: true
  48944. });
  48945. /**
  48946. * Returns the total number of vertices (integer).
  48947. */
  48948. InstancedMesh.prototype.getTotalVertices = function () {
  48949. return this._sourceMesh.getTotalVertices();
  48950. };
  48951. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48952. get: function () {
  48953. return this._sourceMesh;
  48954. },
  48955. enumerable: true,
  48956. configurable: true
  48957. });
  48958. /**
  48959. * Is this node ready to be used/rendered
  48960. * @return {boolean} is it ready
  48961. */
  48962. InstancedMesh.prototype.isReady = function () {
  48963. return this._sourceMesh.isReady(true);
  48964. };
  48965. /**
  48966. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48967. */
  48968. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48969. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48970. };
  48971. /**
  48972. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48973. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48974. * The `data` are either a numeric array either a Float32Array.
  48975. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48976. * 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).
  48977. * Note that a new underlying VertexBuffer object is created each call.
  48978. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48979. *
  48980. * Possible `kind` values :
  48981. * - BABYLON.VertexBuffer.PositionKind
  48982. * - BABYLON.VertexBuffer.UVKind
  48983. * - BABYLON.VertexBuffer.UV2Kind
  48984. * - BABYLON.VertexBuffer.UV3Kind
  48985. * - BABYLON.VertexBuffer.UV4Kind
  48986. * - BABYLON.VertexBuffer.UV5Kind
  48987. * - BABYLON.VertexBuffer.UV6Kind
  48988. * - BABYLON.VertexBuffer.ColorKind
  48989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48993. *
  48994. * Returns the Mesh.
  48995. */
  48996. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  48997. if (this.sourceMesh) {
  48998. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  48999. }
  49000. return this.sourceMesh;
  49001. };
  49002. /**
  49003. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  49004. * If the mesh has no geometry, it is simply returned as it is.
  49005. * The `data` are either a numeric array either a Float32Array.
  49006. * No new underlying VertexBuffer object is created.
  49007. * 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.
  49008. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  49009. *
  49010. * Possible `kind` values :
  49011. * - BABYLON.VertexBuffer.PositionKind
  49012. * - BABYLON.VertexBuffer.UVKind
  49013. * - BABYLON.VertexBuffer.UV2Kind
  49014. * - BABYLON.VertexBuffer.UV3Kind
  49015. * - BABYLON.VertexBuffer.UV4Kind
  49016. * - BABYLON.VertexBuffer.UV5Kind
  49017. * - BABYLON.VertexBuffer.UV6Kind
  49018. * - BABYLON.VertexBuffer.ColorKind
  49019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49023. *
  49024. * Returns the Mesh.
  49025. */
  49026. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49027. if (this.sourceMesh) {
  49028. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49029. }
  49030. return this.sourceMesh;
  49031. };
  49032. /**
  49033. * Sets the mesh indices.
  49034. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49035. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49036. * This method creates a new index buffer each call.
  49037. * Returns the Mesh.
  49038. */
  49039. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49040. if (totalVertices === void 0) { totalVertices = null; }
  49041. if (this.sourceMesh) {
  49042. this.sourceMesh.setIndices(indices, totalVertices);
  49043. }
  49044. return this.sourceMesh;
  49045. };
  49046. /**
  49047. * Boolean : True if the mesh owns the requested kind of data.
  49048. */
  49049. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49050. return this._sourceMesh.isVerticesDataPresent(kind);
  49051. };
  49052. /**
  49053. * Returns an array of indices (IndicesArray).
  49054. */
  49055. InstancedMesh.prototype.getIndices = function () {
  49056. return this._sourceMesh.getIndices();
  49057. };
  49058. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49059. get: function () {
  49060. return this._sourceMesh._positions;
  49061. },
  49062. enumerable: true,
  49063. configurable: true
  49064. });
  49065. /**
  49066. * Sets a new updated BoundingInfo to the mesh.
  49067. * Returns the mesh.
  49068. */
  49069. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49070. var meshBB = this._sourceMesh.getBoundingInfo();
  49071. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49072. this._updateBoundingInfo();
  49073. return this;
  49074. };
  49075. InstancedMesh.prototype._preActivate = function () {
  49076. if (this._currentLOD) {
  49077. this._currentLOD._preActivate();
  49078. }
  49079. return this;
  49080. };
  49081. InstancedMesh.prototype._activate = function (renderId) {
  49082. if (this._currentLOD) {
  49083. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49084. }
  49085. return this;
  49086. };
  49087. /**
  49088. * Returns the current associated LOD AbstractMesh.
  49089. */
  49090. InstancedMesh.prototype.getLOD = function (camera) {
  49091. if (!camera) {
  49092. return this;
  49093. }
  49094. var boundingInfo = this.getBoundingInfo();
  49095. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49096. if (this._currentLOD === this.sourceMesh) {
  49097. return this;
  49098. }
  49099. return this._currentLOD;
  49100. };
  49101. InstancedMesh.prototype._syncSubMeshes = function () {
  49102. this.releaseSubMeshes();
  49103. if (this._sourceMesh.subMeshes) {
  49104. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49105. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49106. }
  49107. }
  49108. return this;
  49109. };
  49110. InstancedMesh.prototype._generatePointsArray = function () {
  49111. return this._sourceMesh._generatePointsArray();
  49112. };
  49113. /**
  49114. * Creates a new InstancedMesh from the current mesh.
  49115. * - name (string) : the cloned mesh name
  49116. * - newParent (optional Node) : the optional Node to parent the clone to.
  49117. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49118. *
  49119. * Returns the clone.
  49120. */
  49121. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49122. var result = this._sourceMesh.createInstance(name);
  49123. // Deep copy
  49124. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49125. // Bounding info
  49126. this.refreshBoundingInfo();
  49127. // Parent
  49128. if (newParent) {
  49129. result.parent = newParent;
  49130. }
  49131. if (!doNotCloneChildren) {
  49132. // Children
  49133. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49134. var mesh = this.getScene().meshes[index];
  49135. if (mesh.parent === this) {
  49136. mesh.clone(mesh.name, result);
  49137. }
  49138. }
  49139. }
  49140. result.computeWorldMatrix(true);
  49141. return result;
  49142. };
  49143. /**
  49144. * Disposes the InstancedMesh.
  49145. * Returns nothing.
  49146. */
  49147. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49148. // Remove from mesh
  49149. var index = this._sourceMesh.instances.indexOf(this);
  49150. this._sourceMesh.instances.splice(index, 1);
  49151. _super.prototype.dispose.call(this, doNotRecurse);
  49152. };
  49153. return InstancedMesh;
  49154. }(BABYLON.AbstractMesh));
  49155. BABYLON.InstancedMesh = InstancedMesh;
  49156. })(BABYLON || (BABYLON = {}));
  49157. //# sourceMappingURL=babylon.instancedMesh.js.map
  49158. var BABYLON;
  49159. (function (BABYLON) {
  49160. var LinesMesh = /** @class */ (function (_super) {
  49161. __extends(LinesMesh, _super);
  49162. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49163. if (scene === void 0) { scene = null; }
  49164. if (parent === void 0) { parent = null; }
  49165. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49166. _this.useVertexColor = useVertexColor;
  49167. _this.useVertexAlpha = useVertexAlpha;
  49168. _this.color = new BABYLON.Color3(1, 1, 1);
  49169. _this.alpha = 1;
  49170. if (source) {
  49171. _this.color = source.color.clone();
  49172. _this.alpha = source.alpha;
  49173. _this.useVertexColor = source.useVertexColor;
  49174. _this.useVertexAlpha = source.useVertexAlpha;
  49175. }
  49176. _this._intersectionThreshold = 0.1;
  49177. var defines = [];
  49178. var options = {
  49179. attributes: [BABYLON.VertexBuffer.PositionKind],
  49180. uniforms: ["world", "viewProjection"],
  49181. needAlphaBlending: true,
  49182. defines: defines
  49183. };
  49184. if (useVertexAlpha === false) {
  49185. options.needAlphaBlending = false;
  49186. }
  49187. if (!useVertexColor) {
  49188. options.uniforms.push("color");
  49189. }
  49190. else {
  49191. options.defines.push("#define VERTEXCOLOR");
  49192. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49193. }
  49194. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49195. return _this;
  49196. }
  49197. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49198. /**
  49199. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49200. * This margin is expressed in world space coordinates, so its value may vary.
  49201. * Default value is 0.1
  49202. * @returns the intersection Threshold value.
  49203. */
  49204. get: function () {
  49205. return this._intersectionThreshold;
  49206. },
  49207. /**
  49208. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49209. * This margin is expressed in world space coordinates, so its value may vary.
  49210. * @param value the new threshold to apply
  49211. */
  49212. set: function (value) {
  49213. if (this._intersectionThreshold === value) {
  49214. return;
  49215. }
  49216. this._intersectionThreshold = value;
  49217. if (this.geometry) {
  49218. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49219. }
  49220. },
  49221. enumerable: true,
  49222. configurable: true
  49223. });
  49224. /**
  49225. * Returns the string "LineMesh"
  49226. */
  49227. LinesMesh.prototype.getClassName = function () {
  49228. return "LinesMesh";
  49229. };
  49230. Object.defineProperty(LinesMesh.prototype, "material", {
  49231. get: function () {
  49232. return this._colorShader;
  49233. },
  49234. set: function (value) {
  49235. // Do nothing
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49241. get: function () {
  49242. return false;
  49243. },
  49244. enumerable: true,
  49245. configurable: true
  49246. });
  49247. LinesMesh.prototype.createInstance = function (name) {
  49248. throw new Error("LinesMeshes do not support createInstance.");
  49249. };
  49250. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49251. if (!this._geometry) {
  49252. return this;
  49253. }
  49254. // VBOs
  49255. this._geometry._bind(this._colorShader.getEffect());
  49256. // Color
  49257. if (!this.useVertexColor) {
  49258. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49259. }
  49260. return this;
  49261. };
  49262. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49263. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49264. return this;
  49265. }
  49266. var engine = this.getScene().getEngine();
  49267. // Draw order
  49268. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49269. return this;
  49270. };
  49271. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49272. this._colorShader.dispose();
  49273. _super.prototype.dispose.call(this, doNotRecurse);
  49274. };
  49275. /**
  49276. * Returns a new LineMesh object cloned from the current one.
  49277. */
  49278. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49279. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49280. };
  49281. return LinesMesh;
  49282. }(BABYLON.Mesh));
  49283. BABYLON.LinesMesh = LinesMesh;
  49284. })(BABYLON || (BABYLON = {}));
  49285. //# sourceMappingURL=babylon.linesMesh.js.map
  49286. var BABYLON;
  49287. (function (BABYLON) {
  49288. var MeshBuilder = /** @class */ (function () {
  49289. function MeshBuilder() {
  49290. }
  49291. MeshBuilder.updateSideOrientation = function (orientation) {
  49292. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49293. return BABYLON.Mesh.DOUBLESIDE;
  49294. }
  49295. if (orientation === undefined || orientation === null) {
  49296. return BABYLON.Mesh.FRONTSIDE;
  49297. }
  49298. return orientation;
  49299. };
  49300. /**
  49301. * Creates a box mesh.
  49302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49303. * The parameter `size` sets the size (float) of each box side (default 1).
  49304. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49305. * 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).
  49306. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49308. * 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).
  49309. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49311. */
  49312. MeshBuilder.CreateBox = function (name, options, scene) {
  49313. if (scene === void 0) { scene = null; }
  49314. var box = new BABYLON.Mesh(name, scene);
  49315. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49316. box._originalBuilderSideOrientation = options.sideOrientation;
  49317. var vertexData = BABYLON.VertexData.CreateBox(options);
  49318. vertexData.applyToMesh(box, options.updatable);
  49319. return box;
  49320. };
  49321. /**
  49322. * Creates a sphere mesh.
  49323. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49324. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49325. * 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`).
  49326. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49327. * 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
  49328. * 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).
  49329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49330. * 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).
  49331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49333. */
  49334. MeshBuilder.CreateSphere = function (name, options, scene) {
  49335. var sphere = new BABYLON.Mesh(name, scene);
  49336. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49337. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49338. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49339. vertexData.applyToMesh(sphere, options.updatable);
  49340. return sphere;
  49341. };
  49342. /**
  49343. * Creates a plane polygonal mesh. By default, this is a disc.
  49344. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49345. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49346. * 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.
  49347. * 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
  49348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49349. * 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).
  49350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49352. */
  49353. MeshBuilder.CreateDisc = function (name, options, scene) {
  49354. if (scene === void 0) { scene = null; }
  49355. var disc = new BABYLON.Mesh(name, scene);
  49356. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49357. disc._originalBuilderSideOrientation = options.sideOrientation;
  49358. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49359. vertexData.applyToMesh(disc, options.updatable);
  49360. return disc;
  49361. };
  49362. /**
  49363. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49364. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49365. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49366. * 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`).
  49367. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49368. * 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.
  49369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49370. * 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).
  49371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49373. */
  49374. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49375. var sphere = new BABYLON.Mesh(name, scene);
  49376. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49377. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49378. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49379. vertexData.applyToMesh(sphere, options.updatable);
  49380. return sphere;
  49381. };
  49382. ;
  49383. /**
  49384. * Creates a ribbon mesh.
  49385. * 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.
  49386. *
  49387. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49388. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49389. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49390. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49391. * 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.
  49392. * 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.
  49393. * 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
  49394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49395. * 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).
  49396. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49397. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49398. * 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.
  49399. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49400. * 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
  49401. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49402. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49404. */
  49405. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49406. if (scene === void 0) { scene = null; }
  49407. var pathArray = options.pathArray;
  49408. var closeArray = options.closeArray;
  49409. var closePath = options.closePath;
  49410. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49411. var instance = options.instance;
  49412. var updatable = options.updatable;
  49413. if (instance) {
  49414. // positionFunction : ribbon case
  49415. // only pathArray and sideOrientation parameters are taken into account for positions update
  49416. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49417. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49418. var positionFunction = function (positions) {
  49419. var minlg = pathArray[0].length;
  49420. var i = 0;
  49421. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49422. for (var si = 1; si <= ns; si++) {
  49423. for (var p = 0; p < pathArray.length; p++) {
  49424. var path = pathArray[p];
  49425. var l = path.length;
  49426. minlg = (minlg < l) ? minlg : l;
  49427. var j = 0;
  49428. while (j < minlg) {
  49429. positions[i] = path[j].x;
  49430. positions[i + 1] = path[j].y;
  49431. positions[i + 2] = path[j].z;
  49432. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49433. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49434. }
  49435. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49436. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49437. }
  49438. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49439. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49440. }
  49441. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49442. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49443. }
  49444. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49445. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49446. }
  49447. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49448. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49449. }
  49450. j++;
  49451. i += 3;
  49452. }
  49453. if (instance._closePath) {
  49454. positions[i] = path[0].x;
  49455. positions[i + 1] = path[0].y;
  49456. positions[i + 2] = path[0].z;
  49457. i += 3;
  49458. }
  49459. }
  49460. }
  49461. };
  49462. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49463. positionFunction(positions);
  49464. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49465. instance._boundingInfo.update(instance._worldMatrix);
  49466. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49467. if (options.colors) {
  49468. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49469. for (var c = 0; c < options.colors.length; c++) {
  49470. colors[c * 4] = options.colors[c].r;
  49471. colors[c * 4 + 1] = options.colors[c].g;
  49472. colors[c * 4 + 2] = options.colors[c].b;
  49473. colors[c * 4 + 3] = options.colors[c].a;
  49474. }
  49475. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49476. }
  49477. if (options.uvs) {
  49478. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49479. for (var i = 0; i < options.uvs.length; i++) {
  49480. uvs[i * 2] = options.uvs[i].x;
  49481. uvs[i * 2 + 1] = options.uvs[i].y;
  49482. }
  49483. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49484. }
  49485. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49486. var indices = instance.getIndices();
  49487. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49488. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49489. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49490. if (instance._closePath) {
  49491. var indexFirst = 0;
  49492. var indexLast = 0;
  49493. for (var p = 0; p < pathArray.length; p++) {
  49494. indexFirst = instance._idx[p] * 3;
  49495. if (p + 1 < pathArray.length) {
  49496. indexLast = (instance._idx[p + 1] - 1) * 3;
  49497. }
  49498. else {
  49499. indexLast = normals.length - 3;
  49500. }
  49501. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49502. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49503. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49504. normals[indexLast] = normals[indexFirst];
  49505. normals[indexLast + 1] = normals[indexFirst + 1];
  49506. normals[indexLast + 2] = normals[indexFirst + 2];
  49507. }
  49508. }
  49509. if (!(instance.areNormalsFrozen)) {
  49510. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49511. }
  49512. }
  49513. return instance;
  49514. }
  49515. else {
  49516. var ribbon = new BABYLON.Mesh(name, scene);
  49517. ribbon._originalBuilderSideOrientation = sideOrientation;
  49518. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49519. if (closePath) {
  49520. ribbon._idx = vertexData._idx;
  49521. }
  49522. ribbon._closePath = closePath;
  49523. ribbon._closeArray = closeArray;
  49524. vertexData.applyToMesh(ribbon, updatable);
  49525. return ribbon;
  49526. }
  49527. };
  49528. /**
  49529. * Creates a cylinder or a cone mesh.
  49530. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49531. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49532. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49533. * 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.
  49534. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49535. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49536. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49537. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49538. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49539. * 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).
  49540. * 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
  49541. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49542. * 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
  49543. * 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.
  49544. * If `enclose` is false, a ring surface is one element.
  49545. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49546. * 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
  49547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49548. * 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).
  49549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49551. */
  49552. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49553. var cylinder = new BABYLON.Mesh(name, scene);
  49554. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49555. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49556. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49557. vertexData.applyToMesh(cylinder, options.updatable);
  49558. return cylinder;
  49559. };
  49560. /**
  49561. * Creates a torus mesh.
  49562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49563. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49564. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49565. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49567. * 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).
  49568. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49570. */
  49571. MeshBuilder.CreateTorus = function (name, options, scene) {
  49572. var torus = new BABYLON.Mesh(name, scene);
  49573. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49574. torus._originalBuilderSideOrientation = options.sideOrientation;
  49575. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49576. vertexData.applyToMesh(torus, options.updatable);
  49577. return torus;
  49578. };
  49579. /**
  49580. * Creates a torus knot mesh.
  49581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49582. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49583. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49584. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49585. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49587. * 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).
  49588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49590. */
  49591. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49592. var torusKnot = new BABYLON.Mesh(name, scene);
  49593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49594. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49595. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49596. vertexData.applyToMesh(torusKnot, options.updatable);
  49597. return torusKnot;
  49598. };
  49599. /**
  49600. * Creates a line system mesh.
  49601. * A line system is a pool of many lines gathered in a single mesh.
  49602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49603. * 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.
  49604. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49605. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49606. * 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
  49607. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49608. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49609. * 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
  49610. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49612. */
  49613. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49614. var instance = options.instance;
  49615. var lines = options.lines;
  49616. var colors = options.colors;
  49617. if (instance) {
  49618. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49619. var vertexColor;
  49620. var lineColors;
  49621. if (colors) {
  49622. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49623. }
  49624. var i = 0;
  49625. var c = 0;
  49626. for (var l = 0; l < lines.length; l++) {
  49627. var points = lines[l];
  49628. for (var p = 0; p < points.length; p++) {
  49629. positions[i] = points[p].x;
  49630. positions[i + 1] = points[p].y;
  49631. positions[i + 2] = points[p].z;
  49632. if (colors && vertexColor) {
  49633. lineColors = colors[l];
  49634. vertexColor[c] = lineColors[p].r;
  49635. vertexColor[c + 1] = lineColors[p].g;
  49636. vertexColor[c + 2] = lineColors[p].b;
  49637. vertexColor[c + 3] = lineColors[p].a;
  49638. c += 4;
  49639. }
  49640. i += 3;
  49641. }
  49642. }
  49643. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49644. if (colors && vertexColor) {
  49645. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49646. }
  49647. return instance;
  49648. }
  49649. // line system creation
  49650. var useVertexColor = (colors) ? true : false;
  49651. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49652. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49653. vertexData.applyToMesh(lineSystem, options.updatable);
  49654. return lineSystem;
  49655. };
  49656. /**
  49657. * Creates a line mesh.
  49658. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49659. * 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.
  49660. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49661. * The parameter `points` is an array successive Vector3.
  49662. * 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
  49663. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49664. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49665. * When updating an instance, remember that only point positions can change, not the number of points.
  49666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49667. */
  49668. MeshBuilder.CreateLines = function (name, options, scene) {
  49669. if (scene === void 0) { scene = null; }
  49670. var colors = (options.colors) ? [options.colors] : null;
  49671. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49672. return lines;
  49673. };
  49674. /**
  49675. * Creates a dashed line mesh.
  49676. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49677. * 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.
  49678. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49679. * The parameter `points` is an array successive Vector3.
  49680. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49681. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49682. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49683. * 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
  49684. * When updating an instance, remember that only point positions can change, not the number of points.
  49685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49686. */
  49687. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49688. if (scene === void 0) { scene = null; }
  49689. var points = options.points;
  49690. var instance = options.instance;
  49691. var gapSize = options.gapSize || 1;
  49692. var dashSize = options.dashSize || 3;
  49693. if (instance) {
  49694. var positionFunction = function (positions) {
  49695. var curvect = BABYLON.Vector3.Zero();
  49696. var nbSeg = positions.length / 6;
  49697. var lg = 0;
  49698. var nb = 0;
  49699. var shft = 0;
  49700. var dashshft = 0;
  49701. var curshft = 0;
  49702. var p = 0;
  49703. var i = 0;
  49704. var j = 0;
  49705. for (i = 0; i < points.length - 1; i++) {
  49706. points[i + 1].subtractToRef(points[i], curvect);
  49707. lg += curvect.length();
  49708. }
  49709. shft = lg / nbSeg;
  49710. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49711. for (i = 0; i < points.length - 1; i++) {
  49712. points[i + 1].subtractToRef(points[i], curvect);
  49713. nb = Math.floor(curvect.length() / shft);
  49714. curvect.normalize();
  49715. j = 0;
  49716. while (j < nb && p < positions.length) {
  49717. curshft = shft * j;
  49718. positions[p] = points[i].x + curshft * curvect.x;
  49719. positions[p + 1] = points[i].y + curshft * curvect.y;
  49720. positions[p + 2] = points[i].z + curshft * curvect.z;
  49721. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49722. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49723. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49724. p += 6;
  49725. j++;
  49726. }
  49727. }
  49728. while (p < positions.length) {
  49729. positions[p] = points[i].x;
  49730. positions[p + 1] = points[i].y;
  49731. positions[p + 2] = points[i].z;
  49732. p += 3;
  49733. }
  49734. };
  49735. instance.updateMeshPositions(positionFunction, false);
  49736. return instance;
  49737. }
  49738. // dashed lines creation
  49739. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49740. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49741. vertexData.applyToMesh(dashedLines, options.updatable);
  49742. dashedLines.dashSize = dashSize;
  49743. dashedLines.gapSize = gapSize;
  49744. return dashedLines;
  49745. };
  49746. /**
  49747. * Creates an extruded shape mesh.
  49748. * 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.
  49749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49750. *
  49751. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49752. * 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
  49753. * extruded along the Z axis.
  49754. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49755. * 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.
  49756. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49757. * 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
  49758. * 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
  49759. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49760. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49761. * 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).
  49762. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49763. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49765. */
  49766. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49767. if (scene === void 0) { scene = null; }
  49768. var path = options.path;
  49769. var shape = options.shape;
  49770. var scale = options.scale || 1;
  49771. var rotation = options.rotation || 0;
  49772. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49773. var updatable = options.updatable;
  49774. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49775. var instance = options.instance || null;
  49776. var invertUV = options.invertUV || false;
  49777. 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);
  49778. };
  49779. /**
  49780. * Creates an custom extruded shape mesh.
  49781. * 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.
  49782. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49783. *
  49784. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49785. * 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
  49786. * extruded along the Z axis.
  49787. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49788. * 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
  49789. * and the distance of this point from the begining of the path :
  49790. * ```javascript
  49791. * var rotationFunction = function(i, distance) {
  49792. * // do things
  49793. * return rotationValue; }
  49794. * ```
  49795. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49796. * 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
  49797. * and the distance of this point from the begining of the path :
  49798. * ```javascript
  49799. * var scaleFunction = function(i, distance) {
  49800. * // do things
  49801. * return scaleValue;}
  49802. * ```
  49803. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49804. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49805. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49806. * 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
  49807. * 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
  49808. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49810. * 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).
  49811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49812. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49814. */
  49815. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49816. var path = options.path;
  49817. var shape = options.shape;
  49818. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49819. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49820. var ribbonCloseArray = options.ribbonCloseArray || false;
  49821. var ribbonClosePath = options.ribbonClosePath || false;
  49822. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49823. var updatable = options.updatable;
  49824. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49825. var instance = options.instance;
  49826. var invertUV = options.invertUV || false;
  49827. 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);
  49828. };
  49829. /**
  49830. * Creates lathe mesh.
  49831. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49833. *
  49834. * 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
  49835. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49836. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49837. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49838. * 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.
  49839. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49840. * 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
  49841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49842. * 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).
  49843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49844. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49846. */
  49847. MeshBuilder.CreateLathe = function (name, options, scene) {
  49848. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49849. var closed = (options.closed === undefined) ? true : options.closed;
  49850. var shape = options.shape;
  49851. var radius = options.radius || 1;
  49852. var tessellation = options.tessellation || 64;
  49853. var updatable = options.updatable;
  49854. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49855. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49856. var pi2 = Math.PI * 2;
  49857. var paths = new Array();
  49858. var invertUV = options.invertUV || false;
  49859. var i = 0;
  49860. var p = 0;
  49861. var step = pi2 / tessellation * arc;
  49862. var rotated;
  49863. var path = new Array();
  49864. ;
  49865. for (i = 0; i <= tessellation; i++) {
  49866. var path = [];
  49867. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49868. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49869. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49870. }
  49871. for (p = 0; p < shape.length; p++) {
  49872. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49873. path.push(rotated);
  49874. }
  49875. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49876. 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));
  49877. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49878. }
  49879. paths.push(path);
  49880. }
  49881. // lathe ribbon
  49882. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49883. return lathe;
  49884. };
  49885. /**
  49886. * Creates a plane mesh.
  49887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49888. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49889. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49890. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49892. * 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).
  49893. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49895. */
  49896. MeshBuilder.CreatePlane = function (name, options, scene) {
  49897. var plane = new BABYLON.Mesh(name, scene);
  49898. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49899. plane._originalBuilderSideOrientation = options.sideOrientation;
  49900. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49901. vertexData.applyToMesh(plane, options.updatable);
  49902. if (options.sourcePlane) {
  49903. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49904. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49905. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49906. plane.rotate(vectorProduct, product);
  49907. }
  49908. return plane;
  49909. };
  49910. /**
  49911. * Creates a ground mesh.
  49912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49913. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49914. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49916. */
  49917. MeshBuilder.CreateGround = function (name, options, scene) {
  49918. var ground = new BABYLON.GroundMesh(name, scene);
  49919. ground._setReady(false);
  49920. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49921. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49922. ground._width = options.width || 1;
  49923. ground._height = options.height || 1;
  49924. ground._maxX = ground._width / 2;
  49925. ground._maxZ = ground._height / 2;
  49926. ground._minX = -ground._maxX;
  49927. ground._minZ = -ground._maxZ;
  49928. var vertexData = BABYLON.VertexData.CreateGround(options);
  49929. vertexData.applyToMesh(ground, options.updatable);
  49930. ground._setReady(true);
  49931. return ground;
  49932. };
  49933. /**
  49934. * Creates a tiled ground mesh.
  49935. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49936. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49937. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49938. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49939. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49940. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49941. * numbers of subdivisions on the ground width and height of each tile.
  49942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49943. */
  49944. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49945. var tiledGround = new BABYLON.Mesh(name, scene);
  49946. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49947. vertexData.applyToMesh(tiledGround, options.updatable);
  49948. return tiledGround;
  49949. };
  49950. /**
  49951. * Creates a ground mesh from a height map.
  49952. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49953. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49954. * The parameter `url` sets the URL of the height map image resource.
  49955. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49956. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49957. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49958. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49959. * 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.
  49960. * 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).
  49961. * This function is passed the newly built mesh :
  49962. * ```javascript
  49963. * function(mesh) { // do things
  49964. * return; }
  49965. * ```
  49966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49967. */
  49968. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49969. var width = options.width || 10.0;
  49970. var height = options.height || 10.0;
  49971. var subdivisions = options.subdivisions || 1 | 0;
  49972. var minHeight = options.minHeight || 0.0;
  49973. var maxHeight = options.maxHeight || 1.0;
  49974. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49975. var updatable = options.updatable;
  49976. var onReady = options.onReady;
  49977. var ground = new BABYLON.GroundMesh(name, scene);
  49978. ground._subdivisionsX = subdivisions;
  49979. ground._subdivisionsY = subdivisions;
  49980. ground._width = width;
  49981. ground._height = height;
  49982. ground._maxX = ground._width / 2.0;
  49983. ground._maxZ = ground._height / 2.0;
  49984. ground._minX = -ground._maxX;
  49985. ground._minZ = -ground._maxZ;
  49986. ground._setReady(false);
  49987. var onload = function (img) {
  49988. // Getting height map data
  49989. var canvas = document.createElement("canvas");
  49990. var context = canvas.getContext("2d");
  49991. if (!context) {
  49992. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49993. }
  49994. if (scene.isDisposed) {
  49995. return;
  49996. }
  49997. var bufferWidth = img.width;
  49998. var bufferHeight = img.height;
  49999. canvas.width = bufferWidth;
  50000. canvas.height = bufferHeight;
  50001. context.drawImage(img, 0, 0);
  50002. // Create VertexData from map data
  50003. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  50004. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  50005. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  50006. width: width, height: height,
  50007. subdivisions: subdivisions,
  50008. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  50009. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  50010. });
  50011. vertexData.applyToMesh(ground, updatable);
  50012. ground._setReady(true);
  50013. //execute ready callback, if set
  50014. if (onReady) {
  50015. onReady(ground);
  50016. }
  50017. };
  50018. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50019. return ground;
  50020. };
  50021. /**
  50022. * Creates a polygon mesh.
  50023. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50024. * 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.
  50025. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50027. * 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).
  50028. * Remember you can only change the shape positions, not their number when updating a polygon.
  50029. */
  50030. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50031. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50032. var shape = options.shape;
  50033. var holes = options.holes || [];
  50034. var depth = options.depth || 0;
  50035. var contours = [];
  50036. var hole = [];
  50037. for (var i = 0; i < shape.length; i++) {
  50038. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50039. }
  50040. var epsilon = 0.00000001;
  50041. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50042. contours.pop();
  50043. }
  50044. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50045. for (var hNb = 0; hNb < holes.length; hNb++) {
  50046. hole = [];
  50047. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50048. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50049. }
  50050. polygonTriangulation.addHole(hole);
  50051. }
  50052. var polygon = polygonTriangulation.build(options.updatable, depth);
  50053. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50054. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50055. vertexData.applyToMesh(polygon, options.updatable);
  50056. return polygon;
  50057. };
  50058. ;
  50059. /**
  50060. * Creates an extruded polygon mesh, with depth in the Y direction.
  50061. * 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).
  50062. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50063. */
  50064. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50065. return MeshBuilder.CreatePolygon(name, options, scene);
  50066. };
  50067. ;
  50068. /**
  50069. * Creates a tube mesh.
  50070. * 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.
  50071. *
  50072. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50073. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50074. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50075. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50076. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50077. * 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.
  50078. * It must return a radius value (positive float) :
  50079. * ```javascript
  50080. * var radiusFunction = function(i, distance) {
  50081. * // do things
  50082. * return radius; }
  50083. * ```
  50084. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50085. * 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
  50086. * 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
  50087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50088. * 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).
  50089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50090. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50092. */
  50093. MeshBuilder.CreateTube = function (name, options, scene) {
  50094. var path = options.path;
  50095. var instance = options.instance;
  50096. var radius = 1.0;
  50097. if (instance) {
  50098. radius = instance.radius;
  50099. }
  50100. if (options.radius !== undefined) {
  50101. radius = options.radius;
  50102. }
  50103. ;
  50104. var tessellation = options.tessellation || 64 | 0;
  50105. var radiusFunction = options.radiusFunction || null;
  50106. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50107. var invertUV = options.invertUV || false;
  50108. var updatable = options.updatable;
  50109. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50110. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50111. // tube geometry
  50112. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50113. var tangents = path3D.getTangents();
  50114. var normals = path3D.getNormals();
  50115. var distances = path3D.getDistances();
  50116. var pi2 = Math.PI * 2;
  50117. var step = pi2 / tessellation * arc;
  50118. var returnRadius = function () { return radius; };
  50119. var radiusFunctionFinal = radiusFunction || returnRadius;
  50120. var circlePath;
  50121. var rad;
  50122. var normal;
  50123. var rotated;
  50124. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50125. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50126. for (var i = 0; i < path.length; i++) {
  50127. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50128. circlePath = Array(); // current circle array
  50129. normal = normals[i]; // current normal
  50130. for (var t = 0; t < tessellation; t++) {
  50131. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50132. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50133. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50134. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50135. circlePath[t] = rotated;
  50136. }
  50137. circlePaths[index] = circlePath;
  50138. index++;
  50139. }
  50140. // cap
  50141. var capPath = function (nbPoints, pathIndex) {
  50142. var pointCap = Array();
  50143. for (var i = 0; i < nbPoints; i++) {
  50144. pointCap.push(path[pathIndex]);
  50145. }
  50146. return pointCap;
  50147. };
  50148. switch (cap) {
  50149. case BABYLON.Mesh.NO_CAP:
  50150. break;
  50151. case BABYLON.Mesh.CAP_START:
  50152. circlePaths[0] = capPath(tessellation, 0);
  50153. circlePaths[1] = circlePaths[2].slice(0);
  50154. break;
  50155. case BABYLON.Mesh.CAP_END:
  50156. circlePaths[index] = circlePaths[index - 1].slice(0);
  50157. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50158. break;
  50159. case BABYLON.Mesh.CAP_ALL:
  50160. circlePaths[0] = capPath(tessellation, 0);
  50161. circlePaths[1] = circlePaths[2].slice(0);
  50162. circlePaths[index] = circlePaths[index - 1].slice(0);
  50163. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50164. break;
  50165. default:
  50166. break;
  50167. }
  50168. return circlePaths;
  50169. };
  50170. var path3D;
  50171. var pathArray;
  50172. if (instance) {
  50173. var arc = options.arc || instance.arc;
  50174. path3D = (instance.path3D).update(path);
  50175. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50176. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50177. instance.path3D = path3D;
  50178. instance.pathArray = pathArray;
  50179. instance.arc = arc;
  50180. instance.radius = radius;
  50181. return instance;
  50182. }
  50183. // tube creation
  50184. path3D = new BABYLON.Path3D(path);
  50185. var newPathArray = new Array();
  50186. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50187. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50188. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50189. tube.pathArray = pathArray;
  50190. tube.path3D = path3D;
  50191. tube.tessellation = tessellation;
  50192. tube.cap = cap;
  50193. tube.arc = options.arc;
  50194. tube.radius = radius;
  50195. return tube;
  50196. };
  50197. /**
  50198. * Creates a polyhedron mesh.
  50199. *
  50200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50201. * 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
  50202. * to choose the wanted type.
  50203. * The parameter `size` (positive float, default 1) sets the polygon size.
  50204. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50205. * 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`.
  50206. * 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
  50207. * 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)`).
  50208. * 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
  50209. * 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.
  50210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50211. * 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).
  50212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50214. */
  50215. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50216. var polyhedron = new BABYLON.Mesh(name, scene);
  50217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50218. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50219. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50220. vertexData.applyToMesh(polyhedron, options.updatable);
  50221. return polyhedron;
  50222. };
  50223. /**
  50224. * Creates a decal mesh.
  50225. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50226. * 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.
  50227. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50228. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50229. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50230. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50231. */
  50232. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50233. var indices = sourceMesh.getIndices();
  50234. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50235. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50236. var position = options.position || BABYLON.Vector3.Zero();
  50237. var normal = options.normal || BABYLON.Vector3.Up();
  50238. var size = options.size || BABYLON.Vector3.One();
  50239. var angle = options.angle || 0;
  50240. // Getting correct rotation
  50241. if (!normal) {
  50242. var target = new BABYLON.Vector3(0, 0, 1);
  50243. var camera = sourceMesh.getScene().activeCamera;
  50244. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50245. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50246. }
  50247. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50248. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50249. var pitch = Math.atan2(normal.y, len);
  50250. // Matrix
  50251. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50252. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50253. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50254. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50255. var vertexData = new BABYLON.VertexData();
  50256. vertexData.indices = [];
  50257. vertexData.positions = [];
  50258. vertexData.normals = [];
  50259. vertexData.uvs = [];
  50260. var currentVertexDataIndex = 0;
  50261. var extractDecalVector3 = function (indexId) {
  50262. var result = new BABYLON.PositionNormalVertex();
  50263. if (!indices || !positions || !normals) {
  50264. return result;
  50265. }
  50266. var vertexId = indices[indexId];
  50267. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50268. // Send vector to decal local world
  50269. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50270. // Get normal
  50271. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50272. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50273. return result;
  50274. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50275. var clip = function (vertices, axis) {
  50276. if (vertices.length === 0) {
  50277. return vertices;
  50278. }
  50279. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50280. var clipVertices = function (v0, v1) {
  50281. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50282. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50283. };
  50284. var result = new Array();
  50285. for (var index = 0; index < vertices.length; index += 3) {
  50286. var v1Out;
  50287. var v2Out;
  50288. var v3Out;
  50289. var total = 0;
  50290. var nV1 = null;
  50291. var nV2 = null;
  50292. var nV3 = null;
  50293. var nV4 = null;
  50294. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50295. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50296. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50297. v1Out = d1 > 0;
  50298. v2Out = d2 > 0;
  50299. v3Out = d3 > 0;
  50300. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50301. switch (total) {
  50302. case 0:
  50303. result.push(vertices[index]);
  50304. result.push(vertices[index + 1]);
  50305. result.push(vertices[index + 2]);
  50306. break;
  50307. case 1:
  50308. if (v1Out) {
  50309. nV1 = vertices[index + 1];
  50310. nV2 = vertices[index + 2];
  50311. nV3 = clipVertices(vertices[index], nV1);
  50312. nV4 = clipVertices(vertices[index], nV2);
  50313. }
  50314. if (v2Out) {
  50315. nV1 = vertices[index];
  50316. nV2 = vertices[index + 2];
  50317. nV3 = clipVertices(vertices[index + 1], nV1);
  50318. nV4 = clipVertices(vertices[index + 1], nV2);
  50319. result.push(nV3);
  50320. result.push(nV2.clone());
  50321. result.push(nV1.clone());
  50322. result.push(nV2.clone());
  50323. result.push(nV3.clone());
  50324. result.push(nV4);
  50325. break;
  50326. }
  50327. if (v3Out) {
  50328. nV1 = vertices[index];
  50329. nV2 = vertices[index + 1];
  50330. nV3 = clipVertices(vertices[index + 2], nV1);
  50331. nV4 = clipVertices(vertices[index + 2], nV2);
  50332. }
  50333. if (nV1 && nV2 && nV3 && nV4) {
  50334. result.push(nV1.clone());
  50335. result.push(nV2.clone());
  50336. result.push(nV3);
  50337. result.push(nV4);
  50338. result.push(nV3.clone());
  50339. result.push(nV2.clone());
  50340. }
  50341. break;
  50342. case 2:
  50343. if (!v1Out) {
  50344. nV1 = vertices[index].clone();
  50345. nV2 = clipVertices(nV1, vertices[index + 1]);
  50346. nV3 = clipVertices(nV1, vertices[index + 2]);
  50347. result.push(nV1);
  50348. result.push(nV2);
  50349. result.push(nV3);
  50350. }
  50351. if (!v2Out) {
  50352. nV1 = vertices[index + 1].clone();
  50353. nV2 = clipVertices(nV1, vertices[index + 2]);
  50354. nV3 = clipVertices(nV1, vertices[index]);
  50355. result.push(nV1);
  50356. result.push(nV2);
  50357. result.push(nV3);
  50358. }
  50359. if (!v3Out) {
  50360. nV1 = vertices[index + 2].clone();
  50361. nV2 = clipVertices(nV1, vertices[index]);
  50362. nV3 = clipVertices(nV1, vertices[index + 1]);
  50363. result.push(nV1);
  50364. result.push(nV2);
  50365. result.push(nV3);
  50366. }
  50367. break;
  50368. case 3:
  50369. break;
  50370. }
  50371. }
  50372. return result;
  50373. };
  50374. for (var index = 0; index < indices.length; index += 3) {
  50375. var faceVertices = new Array();
  50376. faceVertices.push(extractDecalVector3(index));
  50377. faceVertices.push(extractDecalVector3(index + 1));
  50378. faceVertices.push(extractDecalVector3(index + 2));
  50379. // Clip
  50380. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50381. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50382. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50383. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50384. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50385. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50386. if (faceVertices.length === 0) {
  50387. continue;
  50388. }
  50389. // Add UVs and get back to world
  50390. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50391. var vertex = faceVertices[vIndex];
  50392. //TODO check for Int32Array | Uint32Array | Uint16Array
  50393. vertexData.indices.push(currentVertexDataIndex);
  50394. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50395. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50396. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50397. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50398. currentVertexDataIndex++;
  50399. }
  50400. }
  50401. // Return mesh
  50402. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50403. vertexData.applyToMesh(decal);
  50404. decal.position = position.clone();
  50405. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50406. return decal;
  50407. };
  50408. // Privates
  50409. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50410. // extrusion geometry
  50411. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50412. var tangents = path3D.getTangents();
  50413. var normals = path3D.getNormals();
  50414. var binormals = path3D.getBinormals();
  50415. var distances = path3D.getDistances();
  50416. var angle = 0;
  50417. var returnScale = function () { return scale !== null ? scale : 1; };
  50418. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50419. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50420. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50421. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50422. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50423. for (var i = 0; i < curve.length; i++) {
  50424. var shapePath = new Array();
  50425. var angleStep = rotate(i, distances[i]);
  50426. var scaleRatio = scl(i, distances[i]);
  50427. for (var p = 0; p < shape.length; p++) {
  50428. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50429. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50430. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50431. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50432. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50433. shapePath[p] = rotated;
  50434. }
  50435. shapePaths[index] = shapePath;
  50436. angle += angleStep;
  50437. index++;
  50438. }
  50439. // cap
  50440. var capPath = function (shapePath) {
  50441. var pointCap = Array();
  50442. var barycenter = BABYLON.Vector3.Zero();
  50443. var i;
  50444. for (i = 0; i < shapePath.length; i++) {
  50445. barycenter.addInPlace(shapePath[i]);
  50446. }
  50447. barycenter.scaleInPlace(1.0 / shapePath.length);
  50448. for (i = 0; i < shapePath.length; i++) {
  50449. pointCap.push(barycenter);
  50450. }
  50451. return pointCap;
  50452. };
  50453. switch (cap) {
  50454. case BABYLON.Mesh.NO_CAP:
  50455. break;
  50456. case BABYLON.Mesh.CAP_START:
  50457. shapePaths[0] = capPath(shapePaths[2]);
  50458. shapePaths[1] = shapePaths[2];
  50459. break;
  50460. case BABYLON.Mesh.CAP_END:
  50461. shapePaths[index] = shapePaths[index - 1];
  50462. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50463. break;
  50464. case BABYLON.Mesh.CAP_ALL:
  50465. shapePaths[0] = capPath(shapePaths[2]);
  50466. shapePaths[1] = shapePaths[2];
  50467. shapePaths[index] = shapePaths[index - 1];
  50468. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50469. break;
  50470. default:
  50471. break;
  50472. }
  50473. return shapePaths;
  50474. };
  50475. var path3D;
  50476. var pathArray;
  50477. if (instance) {
  50478. path3D = (instance.path3D).update(curve);
  50479. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50480. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50481. return instance;
  50482. }
  50483. // extruded shape creation
  50484. path3D = new BABYLON.Path3D(curve);
  50485. var newShapePaths = new Array();
  50486. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50487. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50488. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50489. extrudedGeneric.pathArray = pathArray;
  50490. extrudedGeneric.path3D = path3D;
  50491. extrudedGeneric.cap = cap;
  50492. return extrudedGeneric;
  50493. };
  50494. return MeshBuilder;
  50495. }());
  50496. BABYLON.MeshBuilder = MeshBuilder;
  50497. })(BABYLON || (BABYLON = {}));
  50498. //# sourceMappingURL=babylon.meshBuilder.js.map
  50499. var BABYLON;
  50500. (function (BABYLON) {
  50501. var AudioEngine = /** @class */ (function () {
  50502. function AudioEngine() {
  50503. this._audioContext = null;
  50504. this._audioContextInitialized = false;
  50505. this.canUseWebAudio = false;
  50506. this.WarnedWebAudioUnsupported = false;
  50507. this.unlocked = false;
  50508. this.isMP3supported = false;
  50509. this.isOGGsupported = false;
  50510. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50511. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50512. this.canUseWebAudio = true;
  50513. }
  50514. var audioElem = document.createElement('audio');
  50515. try {
  50516. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50517. this.isMP3supported = true;
  50518. }
  50519. }
  50520. catch (e) {
  50521. // protect error during capability check.
  50522. }
  50523. try {
  50524. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50525. this.isOGGsupported = true;
  50526. }
  50527. }
  50528. catch (e) {
  50529. // protect error during capability check.
  50530. }
  50531. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50532. this._unlockiOSaudio();
  50533. }
  50534. else {
  50535. this.unlocked = true;
  50536. }
  50537. }
  50538. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50539. get: function () {
  50540. if (!this._audioContextInitialized) {
  50541. this._initializeAudioContext();
  50542. }
  50543. return this._audioContext;
  50544. },
  50545. enumerable: true,
  50546. configurable: true
  50547. });
  50548. AudioEngine.prototype._unlockiOSaudio = function () {
  50549. var _this = this;
  50550. var unlockaudio = function () {
  50551. if (!_this.audioContext) {
  50552. return;
  50553. }
  50554. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50555. var source = _this.audioContext.createBufferSource();
  50556. source.buffer = buffer;
  50557. source.connect(_this.audioContext.destination);
  50558. source.start(0);
  50559. setTimeout(function () {
  50560. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50561. _this.unlocked = true;
  50562. window.removeEventListener('touchend', unlockaudio, false);
  50563. if (_this.onAudioUnlocked) {
  50564. _this.onAudioUnlocked();
  50565. }
  50566. }
  50567. }, 0);
  50568. };
  50569. window.addEventListener('touchend', unlockaudio, false);
  50570. };
  50571. AudioEngine.prototype._initializeAudioContext = function () {
  50572. try {
  50573. if (this.canUseWebAudio) {
  50574. this._audioContext = new AudioContext();
  50575. // create a global volume gain node
  50576. this.masterGain = this._audioContext.createGain();
  50577. this.masterGain.gain.value = 1;
  50578. this.masterGain.connect(this._audioContext.destination);
  50579. this._audioContextInitialized = true;
  50580. }
  50581. }
  50582. catch (e) {
  50583. this.canUseWebAudio = false;
  50584. BABYLON.Tools.Error("Web Audio: " + e.message);
  50585. }
  50586. };
  50587. AudioEngine.prototype.dispose = function () {
  50588. if (this.canUseWebAudio && this._audioContextInitialized) {
  50589. if (this._connectedAnalyser && this._audioContext) {
  50590. this._connectedAnalyser.stopDebugCanvas();
  50591. this._connectedAnalyser.dispose();
  50592. this.masterGain.disconnect();
  50593. this.masterGain.connect(this._audioContext.destination);
  50594. this._connectedAnalyser = null;
  50595. }
  50596. this.masterGain.gain.value = 1;
  50597. }
  50598. this.WarnedWebAudioUnsupported = false;
  50599. };
  50600. AudioEngine.prototype.getGlobalVolume = function () {
  50601. if (this.canUseWebAudio && this._audioContextInitialized) {
  50602. return this.masterGain.gain.value;
  50603. }
  50604. else {
  50605. return -1;
  50606. }
  50607. };
  50608. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50609. if (this.canUseWebAudio && this._audioContextInitialized) {
  50610. this.masterGain.gain.value = newVolume;
  50611. }
  50612. };
  50613. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50614. if (this._connectedAnalyser) {
  50615. this._connectedAnalyser.stopDebugCanvas();
  50616. }
  50617. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50618. this._connectedAnalyser = analyser;
  50619. this.masterGain.disconnect();
  50620. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50621. }
  50622. };
  50623. return AudioEngine;
  50624. }());
  50625. BABYLON.AudioEngine = AudioEngine;
  50626. })(BABYLON || (BABYLON = {}));
  50627. //# sourceMappingURL=babylon.audioEngine.js.map
  50628. var BABYLON;
  50629. (function (BABYLON) {
  50630. var Sound = /** @class */ (function () {
  50631. /**
  50632. * Create a sound and attach it to a scene
  50633. * @param name Name of your sound
  50634. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50635. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50636. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50637. */
  50638. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50639. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50640. var _this = this;
  50641. this.autoplay = false;
  50642. this.loop = false;
  50643. this.useCustomAttenuation = false;
  50644. this.spatialSound = false;
  50645. this.refDistance = 1;
  50646. this.rolloffFactor = 1;
  50647. this.maxDistance = 100;
  50648. this.distanceModel = "linear";
  50649. this._panningModel = "equalpower";
  50650. this._playbackRate = 1;
  50651. this._streaming = false;
  50652. this._startTime = 0;
  50653. this._startOffset = 0;
  50654. this._position = BABYLON.Vector3.Zero();
  50655. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50656. this._volume = 1;
  50657. this._isReadyToPlay = false;
  50658. this.isPlaying = false;
  50659. this.isPaused = false;
  50660. this._isDirectional = false;
  50661. // Used if you'd like to create a directional sound.
  50662. // If not set, the sound will be omnidirectional
  50663. this._coneInnerAngle = 360;
  50664. this._coneOuterAngle = 360;
  50665. this._coneOuterGain = 0;
  50666. this._isOutputConnected = false;
  50667. this._urlType = "Unknown";
  50668. this.name = name;
  50669. this._scene = scene;
  50670. this._readyToPlayCallback = readyToPlayCallback;
  50671. // Default custom attenuation function is a linear attenuation
  50672. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50673. if (currentDistance < maxDistance) {
  50674. return currentVolume * (1 - currentDistance / maxDistance);
  50675. }
  50676. else {
  50677. return 0;
  50678. }
  50679. };
  50680. if (options) {
  50681. this.autoplay = options.autoplay || false;
  50682. this.loop = options.loop || false;
  50683. // if volume === 0, we need another way to check this option
  50684. if (options.volume !== undefined) {
  50685. this._volume = options.volume;
  50686. }
  50687. this.spatialSound = options.spatialSound || false;
  50688. this.maxDistance = options.maxDistance || 100;
  50689. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50690. this.rolloffFactor = options.rolloffFactor || 1;
  50691. this.refDistance = options.refDistance || 1;
  50692. this.distanceModel = options.distanceModel || "linear";
  50693. this._playbackRate = options.playbackRate || 1;
  50694. this._streaming = options.streaming || false;
  50695. }
  50696. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50697. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50698. this._soundGain.gain.value = this._volume;
  50699. this._inputAudioNode = this._soundGain;
  50700. this._ouputAudioNode = this._soundGain;
  50701. if (this.spatialSound) {
  50702. this._createSpatialParameters();
  50703. }
  50704. this._scene.mainSoundTrack.AddSound(this);
  50705. var validParameter = true;
  50706. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50707. if (urlOrArrayBuffer) {
  50708. if (typeof (urlOrArrayBuffer) === "string")
  50709. this._urlType = "String";
  50710. if (Array.isArray(urlOrArrayBuffer))
  50711. this._urlType = "Array";
  50712. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50713. this._urlType = "ArrayBuffer";
  50714. var urls = [];
  50715. var codecSupportedFound = false;
  50716. switch (this._urlType) {
  50717. case "ArrayBuffer":
  50718. if (urlOrArrayBuffer.byteLength > 0) {
  50719. codecSupportedFound = true;
  50720. this._soundLoaded(urlOrArrayBuffer);
  50721. }
  50722. break;
  50723. case "String":
  50724. urls.push(urlOrArrayBuffer);
  50725. case "Array":
  50726. if (urls.length === 0)
  50727. urls = urlOrArrayBuffer;
  50728. // If we found a supported format, we load it immediately and stop the loop
  50729. for (var i = 0; i < urls.length; i++) {
  50730. var url = urls[i];
  50731. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50732. codecSupportedFound = true;
  50733. }
  50734. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50735. codecSupportedFound = true;
  50736. }
  50737. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50738. codecSupportedFound = true;
  50739. }
  50740. if (url.indexOf("blob:") !== -1) {
  50741. codecSupportedFound = true;
  50742. }
  50743. if (codecSupportedFound) {
  50744. // Loading sound using XHR2
  50745. if (!this._streaming) {
  50746. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50747. }
  50748. else {
  50749. this._htmlAudioElement = new Audio(url);
  50750. this._htmlAudioElement.controls = false;
  50751. this._htmlAudioElement.loop = this.loop;
  50752. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50753. this._htmlAudioElement.preload = "auto";
  50754. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50755. _this._isReadyToPlay = true;
  50756. if (_this.autoplay) {
  50757. _this.play();
  50758. }
  50759. if (_this._readyToPlayCallback) {
  50760. _this._readyToPlayCallback();
  50761. }
  50762. });
  50763. document.body.appendChild(this._htmlAudioElement);
  50764. }
  50765. break;
  50766. }
  50767. }
  50768. break;
  50769. default:
  50770. validParameter = false;
  50771. break;
  50772. }
  50773. if (!validParameter) {
  50774. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50775. }
  50776. else {
  50777. if (!codecSupportedFound) {
  50778. this._isReadyToPlay = true;
  50779. // Simulating a ready to play event to avoid breaking code path
  50780. if (this._readyToPlayCallback) {
  50781. window.setTimeout(function () {
  50782. if (_this._readyToPlayCallback) {
  50783. _this._readyToPlayCallback();
  50784. }
  50785. }, 1000);
  50786. }
  50787. }
  50788. }
  50789. }
  50790. }
  50791. else {
  50792. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50793. this._scene.mainSoundTrack.AddSound(this);
  50794. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50795. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50796. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50797. }
  50798. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50799. if (this._readyToPlayCallback) {
  50800. window.setTimeout(function () {
  50801. if (_this._readyToPlayCallback) {
  50802. _this._readyToPlayCallback();
  50803. }
  50804. }, 1000);
  50805. }
  50806. }
  50807. }
  50808. Sound.prototype.dispose = function () {
  50809. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50810. if (this.isPlaying) {
  50811. this.stop();
  50812. }
  50813. this._isReadyToPlay = false;
  50814. if (this.soundTrackId === -1) {
  50815. this._scene.mainSoundTrack.RemoveSound(this);
  50816. }
  50817. else {
  50818. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50819. }
  50820. if (this._soundGain) {
  50821. this._soundGain.disconnect();
  50822. this._soundGain = null;
  50823. }
  50824. if (this._soundPanner) {
  50825. this._soundPanner.disconnect();
  50826. this._soundPanner = null;
  50827. }
  50828. if (this._soundSource) {
  50829. this._soundSource.disconnect();
  50830. this._soundSource = null;
  50831. }
  50832. this._audioBuffer = null;
  50833. if (this._htmlAudioElement) {
  50834. this._htmlAudioElement.pause();
  50835. this._htmlAudioElement.src = "";
  50836. document.body.removeChild(this._htmlAudioElement);
  50837. }
  50838. if (this._connectedMesh && this._registerFunc) {
  50839. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50840. this._connectedMesh = null;
  50841. }
  50842. }
  50843. };
  50844. Sound.prototype.isReady = function () {
  50845. return this._isReadyToPlay;
  50846. };
  50847. Sound.prototype._soundLoaded = function (audioData) {
  50848. var _this = this;
  50849. if (!BABYLON.Engine.audioEngine.audioContext) {
  50850. return;
  50851. }
  50852. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50853. _this._audioBuffer = buffer;
  50854. _this._isReadyToPlay = true;
  50855. if (_this.autoplay) {
  50856. _this.play();
  50857. }
  50858. if (_this._readyToPlayCallback) {
  50859. _this._readyToPlayCallback();
  50860. }
  50861. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50862. };
  50863. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50865. this._audioBuffer = audioBuffer;
  50866. this._isReadyToPlay = true;
  50867. }
  50868. };
  50869. Sound.prototype.updateOptions = function (options) {
  50870. if (options) {
  50871. this.loop = options.loop || this.loop;
  50872. this.maxDistance = options.maxDistance || this.maxDistance;
  50873. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50874. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50875. this.refDistance = options.refDistance || this.refDistance;
  50876. this.distanceModel = options.distanceModel || this.distanceModel;
  50877. this._playbackRate = options.playbackRate || this._playbackRate;
  50878. this._updateSpatialParameters();
  50879. if (this.isPlaying) {
  50880. if (this._streaming) {
  50881. this._htmlAudioElement.playbackRate = this._playbackRate;
  50882. }
  50883. else {
  50884. if (this._soundSource) {
  50885. this._soundSource.playbackRate.value = this._playbackRate;
  50886. }
  50887. }
  50888. }
  50889. }
  50890. };
  50891. Sound.prototype._createSpatialParameters = function () {
  50892. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50893. if (this._scene.headphone) {
  50894. this._panningModel = "HRTF";
  50895. }
  50896. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50897. this._updateSpatialParameters();
  50898. this._soundPanner.connect(this._ouputAudioNode);
  50899. this._inputAudioNode = this._soundPanner;
  50900. }
  50901. };
  50902. Sound.prototype._updateSpatialParameters = function () {
  50903. if (this.spatialSound && this._soundPanner) {
  50904. if (this.useCustomAttenuation) {
  50905. // Tricks to disable in a way embedded Web Audio attenuation
  50906. this._soundPanner.distanceModel = "linear";
  50907. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50908. this._soundPanner.refDistance = 1;
  50909. this._soundPanner.rolloffFactor = 1;
  50910. this._soundPanner.panningModel = this._panningModel;
  50911. }
  50912. else {
  50913. this._soundPanner.distanceModel = this.distanceModel;
  50914. this._soundPanner.maxDistance = this.maxDistance;
  50915. this._soundPanner.refDistance = this.refDistance;
  50916. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50917. this._soundPanner.panningModel = this._panningModel;
  50918. }
  50919. }
  50920. };
  50921. Sound.prototype.switchPanningModelToHRTF = function () {
  50922. this._panningModel = "HRTF";
  50923. this._switchPanningModel();
  50924. };
  50925. Sound.prototype.switchPanningModelToEqualPower = function () {
  50926. this._panningModel = "equalpower";
  50927. this._switchPanningModel();
  50928. };
  50929. Sound.prototype._switchPanningModel = function () {
  50930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50931. this._soundPanner.panningModel = this._panningModel;
  50932. }
  50933. };
  50934. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50935. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50936. if (this._isOutputConnected) {
  50937. this._ouputAudioNode.disconnect();
  50938. }
  50939. this._ouputAudioNode.connect(soundTrackAudioNode);
  50940. this._isOutputConnected = true;
  50941. }
  50942. };
  50943. /**
  50944. * Transform this sound into a directional source
  50945. * @param coneInnerAngle Size of the inner cone in degree
  50946. * @param coneOuterAngle Size of the outer cone in degree
  50947. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50948. */
  50949. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50950. if (coneOuterAngle < coneInnerAngle) {
  50951. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50952. return;
  50953. }
  50954. this._coneInnerAngle = coneInnerAngle;
  50955. this._coneOuterAngle = coneOuterAngle;
  50956. this._coneOuterGain = coneOuterGain;
  50957. this._isDirectional = true;
  50958. if (this.isPlaying && this.loop) {
  50959. this.stop();
  50960. this.play();
  50961. }
  50962. };
  50963. Sound.prototype.setPosition = function (newPosition) {
  50964. this._position = newPosition;
  50965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50966. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50967. }
  50968. };
  50969. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50970. this._localDirection = newLocalDirection;
  50971. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50972. this._updateDirection();
  50973. }
  50974. };
  50975. Sound.prototype._updateDirection = function () {
  50976. if (!this._connectedMesh || !this._soundPanner) {
  50977. return;
  50978. }
  50979. var mat = this._connectedMesh.getWorldMatrix();
  50980. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50981. direction.normalize();
  50982. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50983. };
  50984. Sound.prototype.updateDistanceFromListener = function () {
  50985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50986. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50987. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50988. }
  50989. };
  50990. Sound.prototype.setAttenuationFunction = function (callback) {
  50991. this._customAttenuationFunction = callback;
  50992. };
  50993. /**
  50994. * Play the sound
  50995. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50996. * @param offset (optional) Start the sound setting it at a specific time
  50997. */
  50998. Sound.prototype.play = function (time, offset) {
  50999. var _this = this;
  51000. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  51001. try {
  51002. if (this._startOffset < 0) {
  51003. time = -this._startOffset;
  51004. this._startOffset = 0;
  51005. }
  51006. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51007. if (!this._soundSource || !this._streamingSource) {
  51008. if (this.spatialSound && this._soundPanner) {
  51009. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51010. if (this._isDirectional) {
  51011. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  51012. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  51013. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51014. if (this._connectedMesh) {
  51015. this._updateDirection();
  51016. }
  51017. else {
  51018. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51019. }
  51020. }
  51021. }
  51022. }
  51023. if (this._streaming) {
  51024. if (!this._streamingSource) {
  51025. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51026. this._htmlAudioElement.onended = function () { _this._onended(); };
  51027. this._htmlAudioElement.playbackRate = this._playbackRate;
  51028. }
  51029. this._streamingSource.disconnect();
  51030. this._streamingSource.connect(this._inputAudioNode);
  51031. this._htmlAudioElement.play();
  51032. }
  51033. else {
  51034. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51035. this._soundSource.buffer = this._audioBuffer;
  51036. this._soundSource.connect(this._inputAudioNode);
  51037. this._soundSource.loop = this.loop;
  51038. this._soundSource.playbackRate.value = this._playbackRate;
  51039. this._soundSource.onended = function () { _this._onended(); };
  51040. if (this._soundSource.buffer) {
  51041. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51042. }
  51043. }
  51044. this._startTime = startTime;
  51045. this.isPlaying = true;
  51046. this.isPaused = false;
  51047. }
  51048. catch (ex) {
  51049. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51050. }
  51051. }
  51052. };
  51053. Sound.prototype._onended = function () {
  51054. this.isPlaying = false;
  51055. if (this.onended) {
  51056. this.onended();
  51057. }
  51058. };
  51059. /**
  51060. * Stop the sound
  51061. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51062. */
  51063. Sound.prototype.stop = function (time) {
  51064. if (this.isPlaying) {
  51065. if (this._streaming) {
  51066. this._htmlAudioElement.pause();
  51067. // Test needed for Firefox or it will generate an Invalid State Error
  51068. if (this._htmlAudioElement.currentTime > 0) {
  51069. this._htmlAudioElement.currentTime = 0;
  51070. }
  51071. }
  51072. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51073. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51074. this._soundSource.stop(stopTime);
  51075. this._soundSource.onended = function () { };
  51076. if (!this.isPaused) {
  51077. this._startOffset = 0;
  51078. }
  51079. }
  51080. this.isPlaying = false;
  51081. }
  51082. };
  51083. Sound.prototype.pause = function () {
  51084. if (this.isPlaying) {
  51085. this.isPaused = true;
  51086. if (this._streaming) {
  51087. this._htmlAudioElement.pause();
  51088. }
  51089. else if (BABYLON.Engine.audioEngine.audioContext) {
  51090. this.stop(0);
  51091. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51092. }
  51093. }
  51094. };
  51095. Sound.prototype.setVolume = function (newVolume, time) {
  51096. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51097. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51098. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51099. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51100. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51101. }
  51102. else {
  51103. this._soundGain.gain.value = newVolume;
  51104. }
  51105. }
  51106. this._volume = newVolume;
  51107. };
  51108. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51109. this._playbackRate = newPlaybackRate;
  51110. if (this.isPlaying) {
  51111. if (this._streaming) {
  51112. this._htmlAudioElement.playbackRate = this._playbackRate;
  51113. }
  51114. else if (this._soundSource) {
  51115. this._soundSource.playbackRate.value = this._playbackRate;
  51116. }
  51117. }
  51118. };
  51119. Sound.prototype.getVolume = function () {
  51120. return this._volume;
  51121. };
  51122. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51123. var _this = this;
  51124. if (this._connectedMesh && this._registerFunc) {
  51125. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51126. this._registerFunc = null;
  51127. }
  51128. this._connectedMesh = meshToConnectTo;
  51129. if (!this.spatialSound) {
  51130. this.spatialSound = true;
  51131. this._createSpatialParameters();
  51132. if (this.isPlaying && this.loop) {
  51133. this.stop();
  51134. this.play();
  51135. }
  51136. }
  51137. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51138. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51139. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51140. };
  51141. Sound.prototype.detachFromMesh = function () {
  51142. if (this._connectedMesh && this._registerFunc) {
  51143. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51144. this._registerFunc = null;
  51145. this._connectedMesh = null;
  51146. }
  51147. };
  51148. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51149. if (!node.getBoundingInfo) {
  51150. return;
  51151. }
  51152. var mesh = node;
  51153. var boundingInfo = mesh.getBoundingInfo();
  51154. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51155. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51156. this._updateDirection();
  51157. }
  51158. };
  51159. Sound.prototype.clone = function () {
  51160. var _this = this;
  51161. if (!this._streaming) {
  51162. var setBufferAndRun = function () {
  51163. if (_this._isReadyToPlay) {
  51164. clonedSound._audioBuffer = _this.getAudioBuffer();
  51165. clonedSound._isReadyToPlay = true;
  51166. if (clonedSound.autoplay) {
  51167. clonedSound.play();
  51168. }
  51169. }
  51170. else {
  51171. window.setTimeout(setBufferAndRun, 300);
  51172. }
  51173. };
  51174. var currentOptions = {
  51175. autoplay: this.autoplay, loop: this.loop,
  51176. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51177. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51178. refDistance: this.refDistance, distanceModel: this.distanceModel
  51179. };
  51180. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51181. if (this.useCustomAttenuation) {
  51182. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51183. }
  51184. clonedSound.setPosition(this._position);
  51185. clonedSound.setPlaybackRate(this._playbackRate);
  51186. setBufferAndRun();
  51187. return clonedSound;
  51188. }
  51189. else {
  51190. return null;
  51191. }
  51192. };
  51193. Sound.prototype.getAudioBuffer = function () {
  51194. return this._audioBuffer;
  51195. };
  51196. Sound.prototype.serialize = function () {
  51197. var serializationObject = {
  51198. name: this.name,
  51199. url: this.name,
  51200. autoplay: this.autoplay,
  51201. loop: this.loop,
  51202. volume: this._volume,
  51203. spatialSound: this.spatialSound,
  51204. maxDistance: this.maxDistance,
  51205. rolloffFactor: this.rolloffFactor,
  51206. refDistance: this.refDistance,
  51207. distanceModel: this.distanceModel,
  51208. playbackRate: this._playbackRate,
  51209. panningModel: this._panningModel,
  51210. soundTrackId: this.soundTrackId
  51211. };
  51212. if (this.spatialSound) {
  51213. if (this._connectedMesh)
  51214. serializationObject.connectedMeshId = this._connectedMesh.id;
  51215. serializationObject.position = this._position.asArray();
  51216. serializationObject.refDistance = this.refDistance;
  51217. serializationObject.distanceModel = this.distanceModel;
  51218. serializationObject.isDirectional = this._isDirectional;
  51219. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51220. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51221. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51222. serializationObject.coneOuterGain = this._coneOuterGain;
  51223. }
  51224. return serializationObject;
  51225. };
  51226. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51227. var soundName = parsedSound.name;
  51228. var soundUrl;
  51229. if (parsedSound.url) {
  51230. soundUrl = rootUrl + parsedSound.url;
  51231. }
  51232. else {
  51233. soundUrl = rootUrl + soundName;
  51234. }
  51235. var options = {
  51236. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51237. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51238. rolloffFactor: parsedSound.rolloffFactor,
  51239. refDistance: parsedSound.refDistance,
  51240. distanceModel: parsedSound.distanceModel,
  51241. playbackRate: parsedSound.playbackRate
  51242. };
  51243. var newSound;
  51244. if (!sourceSound) {
  51245. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51246. scene._addPendingData(newSound);
  51247. }
  51248. else {
  51249. var setBufferAndRun = function () {
  51250. if (sourceSound._isReadyToPlay) {
  51251. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51252. newSound._isReadyToPlay = true;
  51253. if (newSound.autoplay) {
  51254. newSound.play();
  51255. }
  51256. }
  51257. else {
  51258. window.setTimeout(setBufferAndRun, 300);
  51259. }
  51260. };
  51261. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51262. setBufferAndRun();
  51263. }
  51264. if (parsedSound.position) {
  51265. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51266. newSound.setPosition(soundPosition);
  51267. }
  51268. if (parsedSound.isDirectional) {
  51269. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51270. if (parsedSound.localDirectionToMesh) {
  51271. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51272. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51273. }
  51274. }
  51275. if (parsedSound.connectedMeshId) {
  51276. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51277. if (connectedMesh) {
  51278. newSound.attachToMesh(connectedMesh);
  51279. }
  51280. }
  51281. return newSound;
  51282. };
  51283. return Sound;
  51284. }());
  51285. BABYLON.Sound = Sound;
  51286. })(BABYLON || (BABYLON = {}));
  51287. //# sourceMappingURL=babylon.sound.js.map
  51288. var BABYLON;
  51289. (function (BABYLON) {
  51290. var SoundTrack = /** @class */ (function () {
  51291. function SoundTrack(scene, options) {
  51292. this.id = -1;
  51293. this._isMainTrack = false;
  51294. this._isInitialized = false;
  51295. this._scene = scene;
  51296. this.soundCollection = new Array();
  51297. this._options = options;
  51298. if (!this._isMainTrack) {
  51299. this._scene.soundTracks.push(this);
  51300. this.id = this._scene.soundTracks.length - 1;
  51301. }
  51302. }
  51303. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51304. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51305. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51306. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51307. if (this._options) {
  51308. if (this._options.volume) {
  51309. this._outputAudioNode.gain.value = this._options.volume;
  51310. }
  51311. if (this._options.mainTrack) {
  51312. this._isMainTrack = this._options.mainTrack;
  51313. }
  51314. }
  51315. this._isInitialized = true;
  51316. }
  51317. };
  51318. SoundTrack.prototype.dispose = function () {
  51319. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51320. if (this._connectedAnalyser) {
  51321. this._connectedAnalyser.stopDebugCanvas();
  51322. }
  51323. while (this.soundCollection.length) {
  51324. this.soundCollection[0].dispose();
  51325. }
  51326. if (this._outputAudioNode) {
  51327. this._outputAudioNode.disconnect();
  51328. }
  51329. this._outputAudioNode = null;
  51330. }
  51331. };
  51332. SoundTrack.prototype.AddSound = function (sound) {
  51333. if (!this._isInitialized) {
  51334. this._initializeSoundTrackAudioGraph();
  51335. }
  51336. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51337. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51338. }
  51339. if (sound.soundTrackId) {
  51340. if (sound.soundTrackId === -1) {
  51341. this._scene.mainSoundTrack.RemoveSound(sound);
  51342. }
  51343. else {
  51344. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51345. }
  51346. }
  51347. this.soundCollection.push(sound);
  51348. sound.soundTrackId = this.id;
  51349. };
  51350. SoundTrack.prototype.RemoveSound = function (sound) {
  51351. var index = this.soundCollection.indexOf(sound);
  51352. if (index !== -1) {
  51353. this.soundCollection.splice(index, 1);
  51354. }
  51355. };
  51356. SoundTrack.prototype.setVolume = function (newVolume) {
  51357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51358. this._outputAudioNode.gain.value = newVolume;
  51359. }
  51360. };
  51361. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51362. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51363. for (var i = 0; i < this.soundCollection.length; i++) {
  51364. this.soundCollection[i].switchPanningModelToHRTF();
  51365. }
  51366. }
  51367. };
  51368. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51370. for (var i = 0; i < this.soundCollection.length; i++) {
  51371. this.soundCollection[i].switchPanningModelToEqualPower();
  51372. }
  51373. }
  51374. };
  51375. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51376. if (this._connectedAnalyser) {
  51377. this._connectedAnalyser.stopDebugCanvas();
  51378. }
  51379. this._connectedAnalyser = analyser;
  51380. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51381. this._outputAudioNode.disconnect();
  51382. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51383. }
  51384. };
  51385. return SoundTrack;
  51386. }());
  51387. BABYLON.SoundTrack = SoundTrack;
  51388. })(BABYLON || (BABYLON = {}));
  51389. //# sourceMappingURL=babylon.soundtrack.js.map
  51390. var BABYLON;
  51391. (function (BABYLON) {
  51392. var Analyser = /** @class */ (function () {
  51393. function Analyser(scene) {
  51394. this.SMOOTHING = 0.75;
  51395. this.FFT_SIZE = 512;
  51396. this.BARGRAPHAMPLITUDE = 256;
  51397. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51398. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51399. this._scene = scene;
  51400. this._audioEngine = BABYLON.Engine.audioEngine;
  51401. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51402. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51403. this._webAudioAnalyser.minDecibels = -140;
  51404. this._webAudioAnalyser.maxDecibels = 0;
  51405. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51406. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51407. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51408. }
  51409. }
  51410. Analyser.prototype.getFrequencyBinCount = function () {
  51411. if (this._audioEngine.canUseWebAudio) {
  51412. return this._webAudioAnalyser.frequencyBinCount;
  51413. }
  51414. else {
  51415. return 0;
  51416. }
  51417. };
  51418. Analyser.prototype.getByteFrequencyData = function () {
  51419. if (this._audioEngine.canUseWebAudio) {
  51420. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51421. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51422. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51423. }
  51424. return this._byteFreqs;
  51425. };
  51426. Analyser.prototype.getByteTimeDomainData = function () {
  51427. if (this._audioEngine.canUseWebAudio) {
  51428. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51429. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51430. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51431. }
  51432. return this._byteTime;
  51433. };
  51434. Analyser.prototype.getFloatFrequencyData = function () {
  51435. if (this._audioEngine.canUseWebAudio) {
  51436. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51437. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51438. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51439. }
  51440. return this._floatFreqs;
  51441. };
  51442. Analyser.prototype.drawDebugCanvas = function () {
  51443. var _this = this;
  51444. if (this._audioEngine.canUseWebAudio) {
  51445. if (!this._debugCanvas) {
  51446. this._debugCanvas = document.createElement("canvas");
  51447. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51448. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51449. this._debugCanvas.style.position = "absolute";
  51450. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51451. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51452. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51453. document.body.appendChild(this._debugCanvas);
  51454. this._registerFunc = function () {
  51455. _this.drawDebugCanvas();
  51456. };
  51457. this._scene.registerBeforeRender(this._registerFunc);
  51458. }
  51459. if (this._registerFunc && this._debugCanvasContext) {
  51460. var workingArray = this.getByteFrequencyData();
  51461. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51462. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51463. // Draw the frequency domain chart.
  51464. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51465. var value = workingArray[i];
  51466. var percent = value / this.BARGRAPHAMPLITUDE;
  51467. var height = this.DEBUGCANVASSIZE.height * percent;
  51468. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51469. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51470. var hue = i / this.getFrequencyBinCount() * 360;
  51471. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51472. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51473. }
  51474. }
  51475. }
  51476. };
  51477. Analyser.prototype.stopDebugCanvas = function () {
  51478. if (this._debugCanvas) {
  51479. if (this._registerFunc) {
  51480. this._scene.unregisterBeforeRender(this._registerFunc);
  51481. this._registerFunc = null;
  51482. }
  51483. document.body.removeChild(this._debugCanvas);
  51484. this._debugCanvas = null;
  51485. this._debugCanvasContext = null;
  51486. }
  51487. };
  51488. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51489. if (this._audioEngine.canUseWebAudio) {
  51490. inputAudioNode.connect(this._webAudioAnalyser);
  51491. this._webAudioAnalyser.connect(outputAudioNode);
  51492. }
  51493. };
  51494. Analyser.prototype.dispose = function () {
  51495. if (this._audioEngine.canUseWebAudio) {
  51496. this._webAudioAnalyser.disconnect();
  51497. }
  51498. };
  51499. return Analyser;
  51500. }());
  51501. BABYLON.Analyser = Analyser;
  51502. })(BABYLON || (BABYLON = {}));
  51503. //# sourceMappingURL=babylon.analyser.js.map
  51504. var BABYLON;
  51505. (function (BABYLON) {
  51506. var CubeTexture = /** @class */ (function (_super) {
  51507. __extends(CubeTexture, _super);
  51508. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51509. if (extensions === void 0) { extensions = null; }
  51510. if (noMipmap === void 0) { noMipmap = false; }
  51511. if (files === void 0) { files = null; }
  51512. if (onLoad === void 0) { onLoad = null; }
  51513. if (onError === void 0) { onError = null; }
  51514. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51515. if (prefiltered === void 0) { prefiltered = false; }
  51516. if (forcedExtension === void 0) { forcedExtension = null; }
  51517. var _this = _super.call(this, scene) || this;
  51518. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51519. _this.name = rootUrl;
  51520. _this.url = rootUrl;
  51521. _this._noMipmap = noMipmap;
  51522. _this.hasAlpha = false;
  51523. _this._format = format;
  51524. _this._prefiltered = prefiltered;
  51525. _this.isCube = true;
  51526. _this._textureMatrix = BABYLON.Matrix.Identity();
  51527. if (prefiltered) {
  51528. _this.gammaSpace = false;
  51529. }
  51530. if (!rootUrl && !files) {
  51531. return _this;
  51532. }
  51533. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51534. var lastDot = rootUrl.lastIndexOf(".");
  51535. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51536. var isDDS = (extension === ".dds");
  51537. if (!files) {
  51538. if (!isDDS && !extensions) {
  51539. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51540. }
  51541. files = [];
  51542. if (extensions) {
  51543. for (var index = 0; index < extensions.length; index++) {
  51544. files.push(rootUrl + extensions[index]);
  51545. }
  51546. }
  51547. }
  51548. _this._files = files;
  51549. if (!_this._texture) {
  51550. if (!scene.useDelayedTextureLoading) {
  51551. if (prefiltered) {
  51552. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51553. }
  51554. else {
  51555. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51556. }
  51557. }
  51558. else {
  51559. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51560. }
  51561. }
  51562. else if (onLoad) {
  51563. if (_this._texture.isReady) {
  51564. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51565. }
  51566. else {
  51567. _this._texture.onLoadedObservable.add(onLoad);
  51568. }
  51569. }
  51570. return _this;
  51571. }
  51572. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51573. return new CubeTexture("", scene, null, noMipmap, files);
  51574. };
  51575. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51576. if (forcedExtension === void 0) { forcedExtension = null; }
  51577. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51578. };
  51579. // Methods
  51580. CubeTexture.prototype.delayLoad = function () {
  51581. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51582. return;
  51583. }
  51584. var scene = this.getScene();
  51585. if (!scene) {
  51586. return;
  51587. }
  51588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51589. this._texture = this._getFromCache(this.url, this._noMipmap);
  51590. if (!this._texture) {
  51591. if (this._prefiltered) {
  51592. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51593. }
  51594. else {
  51595. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51596. }
  51597. }
  51598. };
  51599. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51600. return this._textureMatrix;
  51601. };
  51602. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51603. this._textureMatrix = value;
  51604. };
  51605. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51606. var texture = BABYLON.SerializationHelper.Parse(function () {
  51607. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51608. }, parsedTexture, scene);
  51609. // Animations
  51610. if (parsedTexture.animations) {
  51611. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51612. var parsedAnimation = parsedTexture.animations[animationIndex];
  51613. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51614. }
  51615. }
  51616. return texture;
  51617. };
  51618. CubeTexture.prototype.clone = function () {
  51619. var _this = this;
  51620. return BABYLON.SerializationHelper.Clone(function () {
  51621. var scene = _this.getScene();
  51622. if (!scene) {
  51623. return _this;
  51624. }
  51625. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51626. }, this);
  51627. };
  51628. return CubeTexture;
  51629. }(BABYLON.BaseTexture));
  51630. BABYLON.CubeTexture = CubeTexture;
  51631. })(BABYLON || (BABYLON = {}));
  51632. //# sourceMappingURL=babylon.cubeTexture.js.map
  51633. var BABYLON;
  51634. (function (BABYLON) {
  51635. var RenderTargetTexture = /** @class */ (function (_super) {
  51636. __extends(RenderTargetTexture, _super);
  51637. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51638. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51639. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51640. if (isCube === void 0) { isCube = false; }
  51641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51642. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51643. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51644. if (isMulti === void 0) { isMulti = false; }
  51645. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51646. _this.isCube = isCube;
  51647. /**
  51648. * Use this list to define the list of mesh you want to render.
  51649. */
  51650. _this.renderList = new Array();
  51651. _this.renderParticles = true;
  51652. _this.renderSprites = false;
  51653. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51654. _this.ignoreCameraViewport = false;
  51655. // Events
  51656. /**
  51657. * An event triggered when the texture is unbind.
  51658. * @type {BABYLON.Observable}
  51659. */
  51660. _this.onBeforeBindObservable = new BABYLON.Observable();
  51661. /**
  51662. * An event triggered when the texture is unbind.
  51663. * @type {BABYLON.Observable}
  51664. */
  51665. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51666. /**
  51667. * An event triggered before rendering the texture
  51668. * @type {BABYLON.Observable}
  51669. */
  51670. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51671. /**
  51672. * An event triggered after rendering the texture
  51673. * @type {BABYLON.Observable}
  51674. */
  51675. _this.onAfterRenderObservable = new BABYLON.Observable();
  51676. /**
  51677. * An event triggered after the texture clear
  51678. * @type {BABYLON.Observable}
  51679. */
  51680. _this.onClearObservable = new BABYLON.Observable();
  51681. _this._currentRefreshId = -1;
  51682. _this._refreshRate = 1;
  51683. _this._samples = 1;
  51684. scene = _this.getScene();
  51685. if (!scene) {
  51686. return _this;
  51687. }
  51688. _this._engine = scene.getEngine();
  51689. _this.name = name;
  51690. _this.isRenderTarget = true;
  51691. _this._initialSizeParameter = size;
  51692. _this._processSizeParameter(size);
  51693. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51694. });
  51695. _this._generateMipMaps = generateMipMaps ? true : false;
  51696. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51697. // Rendering groups
  51698. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51699. if (isMulti) {
  51700. return _this;
  51701. }
  51702. _this._renderTargetOptions = {
  51703. generateMipMaps: generateMipMaps,
  51704. type: type,
  51705. samplingMode: samplingMode,
  51706. generateDepthBuffer: generateDepthBuffer,
  51707. generateStencilBuffer: generateStencilBuffer
  51708. };
  51709. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51710. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51711. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51712. }
  51713. if (isCube) {
  51714. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51715. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51716. _this._textureMatrix = BABYLON.Matrix.Identity();
  51717. }
  51718. else {
  51719. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51720. }
  51721. return _this;
  51722. }
  51723. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51724. get: function () {
  51725. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51726. },
  51727. enumerable: true,
  51728. configurable: true
  51729. });
  51730. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51731. get: function () {
  51732. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51733. },
  51734. enumerable: true,
  51735. configurable: true
  51736. });
  51737. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51738. get: function () {
  51739. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51740. },
  51741. enumerable: true,
  51742. configurable: true
  51743. });
  51744. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51745. set: function (callback) {
  51746. if (this._onAfterUnbindObserver) {
  51747. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51748. }
  51749. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51750. },
  51751. enumerable: true,
  51752. configurable: true
  51753. });
  51754. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51755. set: function (callback) {
  51756. if (this._onBeforeRenderObserver) {
  51757. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51758. }
  51759. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51760. },
  51761. enumerable: true,
  51762. configurable: true
  51763. });
  51764. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51765. set: function (callback) {
  51766. if (this._onAfterRenderObserver) {
  51767. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51768. }
  51769. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51770. },
  51771. enumerable: true,
  51772. configurable: true
  51773. });
  51774. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51775. set: function (callback) {
  51776. if (this._onClearObserver) {
  51777. this.onClearObservable.remove(this._onClearObserver);
  51778. }
  51779. this._onClearObserver = this.onClearObservable.add(callback);
  51780. },
  51781. enumerable: true,
  51782. configurable: true
  51783. });
  51784. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51785. get: function () {
  51786. return this._renderTargetOptions;
  51787. },
  51788. enumerable: true,
  51789. configurable: true
  51790. });
  51791. RenderTargetTexture.prototype._onRatioRescale = function () {
  51792. if (this._sizeRatio) {
  51793. this.resize(this._initialSizeParameter);
  51794. }
  51795. };
  51796. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51797. if (size.ratio) {
  51798. this._sizeRatio = size.ratio;
  51799. this._size = {
  51800. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51801. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51802. };
  51803. }
  51804. else {
  51805. this._size = size;
  51806. }
  51807. };
  51808. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51809. get: function () {
  51810. return this._samples;
  51811. },
  51812. set: function (value) {
  51813. if (this._samples === value) {
  51814. return;
  51815. }
  51816. var scene = this.getScene();
  51817. if (!scene) {
  51818. return;
  51819. }
  51820. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51821. },
  51822. enumerable: true,
  51823. configurable: true
  51824. });
  51825. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51826. this._currentRefreshId = -1;
  51827. };
  51828. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51829. get: function () {
  51830. return this._refreshRate;
  51831. },
  51832. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51833. set: function (value) {
  51834. this._refreshRate = value;
  51835. this.resetRefreshCounter();
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51841. if (!this._postProcessManager) {
  51842. var scene = this.getScene();
  51843. if (!scene) {
  51844. return;
  51845. }
  51846. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51847. this._postProcesses = new Array();
  51848. }
  51849. this._postProcesses.push(postProcess);
  51850. this._postProcesses[0].autoClear = false;
  51851. };
  51852. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51853. if (!this._postProcesses) {
  51854. return;
  51855. }
  51856. if (dispose) {
  51857. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51858. var postProcess = _a[_i];
  51859. postProcess.dispose();
  51860. }
  51861. }
  51862. this._postProcesses = [];
  51863. };
  51864. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51865. if (!this._postProcesses) {
  51866. return;
  51867. }
  51868. var index = this._postProcesses.indexOf(postProcess);
  51869. if (index === -1) {
  51870. return;
  51871. }
  51872. this._postProcesses.splice(index, 1);
  51873. if (this._postProcesses.length > 0) {
  51874. this._postProcesses[0].autoClear = false;
  51875. }
  51876. };
  51877. RenderTargetTexture.prototype._shouldRender = function () {
  51878. if (this._currentRefreshId === -1) {
  51879. this._currentRefreshId = 1;
  51880. return true;
  51881. }
  51882. if (this.refreshRate === this._currentRefreshId) {
  51883. this._currentRefreshId = 1;
  51884. return true;
  51885. }
  51886. this._currentRefreshId++;
  51887. return false;
  51888. };
  51889. RenderTargetTexture.prototype.getRenderSize = function () {
  51890. if (this._size.width) {
  51891. return this._size.width;
  51892. }
  51893. return this._size;
  51894. };
  51895. RenderTargetTexture.prototype.getRenderWidth = function () {
  51896. if (this._size.width) {
  51897. return this._size.width;
  51898. }
  51899. return this._size;
  51900. };
  51901. RenderTargetTexture.prototype.getRenderHeight = function () {
  51902. if (this._size.width) {
  51903. return this._size.height;
  51904. }
  51905. return this._size;
  51906. };
  51907. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51908. get: function () {
  51909. return true;
  51910. },
  51911. enumerable: true,
  51912. configurable: true
  51913. });
  51914. RenderTargetTexture.prototype.scale = function (ratio) {
  51915. var newSize = this.getRenderSize() * ratio;
  51916. this.resize(newSize);
  51917. };
  51918. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51919. if (this.isCube) {
  51920. return this._textureMatrix;
  51921. }
  51922. return _super.prototype.getReflectionTextureMatrix.call(this);
  51923. };
  51924. RenderTargetTexture.prototype.resize = function (size) {
  51925. this.releaseInternalTexture();
  51926. var scene = this.getScene();
  51927. if (!scene) {
  51928. return;
  51929. }
  51930. this._processSizeParameter(size);
  51931. if (this.isCube) {
  51932. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51933. }
  51934. else {
  51935. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51936. }
  51937. };
  51938. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51939. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51940. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51941. var scene = this.getScene();
  51942. if (!scene) {
  51943. return;
  51944. }
  51945. var engine = scene.getEngine();
  51946. if (this.useCameraPostProcesses !== undefined) {
  51947. useCameraPostProcess = this.useCameraPostProcesses;
  51948. }
  51949. if (this._waitingRenderList) {
  51950. this.renderList = [];
  51951. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51952. var id = this._waitingRenderList[index];
  51953. var mesh_1 = scene.getMeshByID(id);
  51954. if (mesh_1) {
  51955. this.renderList.push(mesh_1);
  51956. }
  51957. }
  51958. delete this._waitingRenderList;
  51959. }
  51960. // Is predicate defined?
  51961. if (this.renderListPredicate) {
  51962. if (this.renderList) {
  51963. this.renderList.splice(0); // Clear previous renderList
  51964. }
  51965. else {
  51966. this.renderList = [];
  51967. }
  51968. var scene = this.getScene();
  51969. if (!scene) {
  51970. return;
  51971. }
  51972. var sceneMeshes = scene.meshes;
  51973. for (var index = 0; index < sceneMeshes.length; index++) {
  51974. var mesh = sceneMeshes[index];
  51975. if (this.renderListPredicate(mesh)) {
  51976. this.renderList.push(mesh);
  51977. }
  51978. }
  51979. }
  51980. this.onBeforeBindObservable.notifyObservers(this);
  51981. // Set custom projection.
  51982. // Needs to be before binding to prevent changing the aspect ratio.
  51983. var camera;
  51984. if (this.activeCamera) {
  51985. camera = this.activeCamera;
  51986. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51987. if (this.activeCamera !== scene.activeCamera) {
  51988. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51989. }
  51990. }
  51991. else {
  51992. camera = scene.activeCamera;
  51993. if (camera) {
  51994. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51995. }
  51996. }
  51997. // Prepare renderingManager
  51998. this._renderingManager.reset();
  51999. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  52000. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  52001. var sceneRenderId = scene.getRenderId();
  52002. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  52003. var mesh = currentRenderList[meshIndex];
  52004. if (mesh) {
  52005. if (!mesh.isReady()) {
  52006. // Reset _currentRefreshId
  52007. this.resetRefreshCounter();
  52008. continue;
  52009. }
  52010. mesh._preActivateForIntermediateRendering(sceneRenderId);
  52011. var isMasked = void 0;
  52012. if (!this.renderList && camera) {
  52013. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52014. }
  52015. else {
  52016. isMasked = false;
  52017. }
  52018. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52019. mesh._activate(sceneRenderId);
  52020. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52021. var subMesh = mesh.subMeshes[subIndex];
  52022. scene._activeIndices.addCount(subMesh.indexCount, false);
  52023. this._renderingManager.dispatch(subMesh, mesh);
  52024. }
  52025. }
  52026. }
  52027. }
  52028. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52029. var particleSystem = scene.particleSystems[particleIndex];
  52030. var emitter = particleSystem.emitter;
  52031. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52032. continue;
  52033. }
  52034. if (currentRenderList.indexOf(emitter) >= 0) {
  52035. this._renderingManager.dispatchParticles(particleSystem);
  52036. }
  52037. }
  52038. if (this.isCube) {
  52039. for (var face = 0; face < 6; face++) {
  52040. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52041. scene.incrementRenderId();
  52042. scene.resetCachedMaterial();
  52043. }
  52044. }
  52045. else {
  52046. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52047. }
  52048. this.onAfterUnbindObservable.notifyObservers(this);
  52049. if (scene.activeCamera) {
  52050. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52051. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52052. }
  52053. engine.setViewport(scene.activeCamera.viewport);
  52054. }
  52055. scene.resetCachedMaterial();
  52056. };
  52057. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52058. var minimum = 128;
  52059. var x = renderDimension * scale;
  52060. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52061. // Ensure we don't exceed the render dimension (while staying POT)
  52062. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52063. };
  52064. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52065. var _this = this;
  52066. if (!this._texture) {
  52067. return;
  52068. }
  52069. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52070. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52071. });
  52072. };
  52073. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52074. var scene = this.getScene();
  52075. if (!scene) {
  52076. return;
  52077. }
  52078. var engine = scene.getEngine();
  52079. if (!this._texture) {
  52080. return;
  52081. }
  52082. // Bind
  52083. if (this._postProcessManager) {
  52084. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52085. }
  52086. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52087. if (this._texture) {
  52088. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52089. }
  52090. }
  52091. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52092. // Clear
  52093. if (this.onClearObservable.hasObservers()) {
  52094. this.onClearObservable.notifyObservers(engine);
  52095. }
  52096. else {
  52097. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52098. }
  52099. if (!this._doNotChangeAspectRatio) {
  52100. scene.updateTransformMatrix(true);
  52101. }
  52102. // Render
  52103. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52104. if (this._postProcessManager) {
  52105. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52106. }
  52107. else if (useCameraPostProcess) {
  52108. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52109. }
  52110. if (!this._doNotChangeAspectRatio) {
  52111. scene.updateTransformMatrix(true);
  52112. }
  52113. // Dump ?
  52114. if (dumpForDebug) {
  52115. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52116. }
  52117. // Unbind
  52118. if (!this.isCube || faceIndex === 5) {
  52119. if (this.isCube) {
  52120. if (faceIndex === 5) {
  52121. engine.generateMipMapsForCubemap(this._texture);
  52122. }
  52123. }
  52124. this.unbindFrameBuffer(engine, faceIndex);
  52125. }
  52126. else {
  52127. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52128. }
  52129. };
  52130. /**
  52131. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52132. * This allowed control for front to back rendering or reversly depending of the special needs.
  52133. *
  52134. * @param renderingGroupId The rendering group id corresponding to its index
  52135. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52136. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52137. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52138. */
  52139. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52140. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52141. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52142. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52143. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52144. };
  52145. /**
  52146. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52147. *
  52148. * @param renderingGroupId The rendering group id corresponding to its index
  52149. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52150. */
  52151. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52152. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52153. };
  52154. RenderTargetTexture.prototype.clone = function () {
  52155. var textureSize = this.getSize();
  52156. 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);
  52157. // Base texture
  52158. newTexture.hasAlpha = this.hasAlpha;
  52159. newTexture.level = this.level;
  52160. // RenderTarget Texture
  52161. newTexture.coordinatesMode = this.coordinatesMode;
  52162. if (this.renderList) {
  52163. newTexture.renderList = this.renderList.slice(0);
  52164. }
  52165. return newTexture;
  52166. };
  52167. RenderTargetTexture.prototype.serialize = function () {
  52168. if (!this.name) {
  52169. return null;
  52170. }
  52171. var serializationObject = _super.prototype.serialize.call(this);
  52172. serializationObject.renderTargetSize = this.getRenderSize();
  52173. serializationObject.renderList = [];
  52174. if (this.renderList) {
  52175. for (var index = 0; index < this.renderList.length; index++) {
  52176. serializationObject.renderList.push(this.renderList[index].id);
  52177. }
  52178. }
  52179. return serializationObject;
  52180. };
  52181. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52182. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52183. var objBuffer = this.getInternalTexture();
  52184. var scene = this.getScene();
  52185. if (objBuffer && scene) {
  52186. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52187. }
  52188. };
  52189. RenderTargetTexture.prototype.dispose = function () {
  52190. if (this._postProcessManager) {
  52191. this._postProcessManager.dispose();
  52192. this._postProcessManager = null;
  52193. }
  52194. this.clearPostProcesses(true);
  52195. if (this._resizeObserver) {
  52196. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52197. this._resizeObserver = null;
  52198. }
  52199. this.renderList = null;
  52200. // Remove from custom render targets
  52201. var scene = this.getScene();
  52202. if (!scene) {
  52203. return;
  52204. }
  52205. var index = scene.customRenderTargets.indexOf(this);
  52206. if (index >= 0) {
  52207. scene.customRenderTargets.splice(index, 1);
  52208. }
  52209. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52210. var camera = _a[_i];
  52211. index = camera.customRenderTargets.indexOf(this);
  52212. if (index >= 0) {
  52213. camera.customRenderTargets.splice(index, 1);
  52214. }
  52215. }
  52216. _super.prototype.dispose.call(this);
  52217. };
  52218. RenderTargetTexture.prototype._rebuild = function () {
  52219. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52220. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52221. }
  52222. if (this._postProcessManager) {
  52223. this._postProcessManager._rebuild();
  52224. }
  52225. };
  52226. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52227. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52228. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52229. return RenderTargetTexture;
  52230. }(BABYLON.Texture));
  52231. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52232. })(BABYLON || (BABYLON = {}));
  52233. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52234. var BABYLON;
  52235. (function (BABYLON) {
  52236. ;
  52237. var MultiRenderTarget = /** @class */ (function (_super) {
  52238. __extends(MultiRenderTarget, _super);
  52239. function MultiRenderTarget(name, size, count, scene, options) {
  52240. var _this = this;
  52241. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52242. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52243. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52244. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52245. _this._engine = scene.getEngine();
  52246. if (!_this.isSupported) {
  52247. _this.dispose();
  52248. return;
  52249. }
  52250. var types = [];
  52251. var samplingModes = [];
  52252. for (var i = 0; i < count; i++) {
  52253. if (options && options.types && options.types[i] !== undefined) {
  52254. types.push(options.types[i]);
  52255. }
  52256. else {
  52257. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52258. }
  52259. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52260. samplingModes.push(options.samplingModes[i]);
  52261. }
  52262. else {
  52263. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52264. }
  52265. }
  52266. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52267. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52268. _this._size = size;
  52269. _this._multiRenderTargetOptions = {
  52270. samplingModes: samplingModes,
  52271. generateMipMaps: generateMipMaps,
  52272. generateDepthBuffer: generateDepthBuffer,
  52273. generateStencilBuffer: generateStencilBuffer,
  52274. generateDepthTexture: generateDepthTexture,
  52275. types: types,
  52276. textureCount: count
  52277. };
  52278. _this._createInternalTextures();
  52279. _this._createTextures();
  52280. return _this;
  52281. }
  52282. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52283. get: function () {
  52284. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52290. get: function () {
  52291. return this._textures;
  52292. },
  52293. enumerable: true,
  52294. configurable: true
  52295. });
  52296. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52297. get: function () {
  52298. return this._textures[this._textures.length - 1];
  52299. },
  52300. enumerable: true,
  52301. configurable: true
  52302. });
  52303. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52304. set: function (wrap) {
  52305. if (this._textures) {
  52306. for (var i = 0; i < this._textures.length; i++) {
  52307. this._textures[i].wrapU = wrap;
  52308. }
  52309. }
  52310. },
  52311. enumerable: true,
  52312. configurable: true
  52313. });
  52314. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52315. set: function (wrap) {
  52316. if (this._textures) {
  52317. for (var i = 0; i < this._textures.length; i++) {
  52318. this._textures[i].wrapV = wrap;
  52319. }
  52320. }
  52321. },
  52322. enumerable: true,
  52323. configurable: true
  52324. });
  52325. MultiRenderTarget.prototype._rebuild = function () {
  52326. this.releaseInternalTextures();
  52327. this._createInternalTextures();
  52328. for (var i = 0; i < this._internalTextures.length; i++) {
  52329. var texture = this._textures[i];
  52330. texture._texture = this._internalTextures[i];
  52331. }
  52332. // Keeps references to frame buffer and stencil/depth buffer
  52333. this._texture = this._internalTextures[0];
  52334. };
  52335. MultiRenderTarget.prototype._createInternalTextures = function () {
  52336. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52337. };
  52338. MultiRenderTarget.prototype._createTextures = function () {
  52339. this._textures = [];
  52340. for (var i = 0; i < this._internalTextures.length; i++) {
  52341. var texture = new BABYLON.Texture(null, this.getScene());
  52342. texture._texture = this._internalTextures[i];
  52343. this._textures.push(texture);
  52344. }
  52345. // Keeps references to frame buffer and stencil/depth buffer
  52346. this._texture = this._internalTextures[0];
  52347. };
  52348. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52349. get: function () {
  52350. return this._samples;
  52351. },
  52352. set: function (value) {
  52353. if (this._samples === value) {
  52354. return;
  52355. }
  52356. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52357. },
  52358. enumerable: true,
  52359. configurable: true
  52360. });
  52361. MultiRenderTarget.prototype.resize = function (size) {
  52362. this.releaseInternalTextures();
  52363. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52364. this._createInternalTextures();
  52365. };
  52366. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52367. var _this = this;
  52368. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52369. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52370. });
  52371. };
  52372. MultiRenderTarget.prototype.dispose = function () {
  52373. this.releaseInternalTextures();
  52374. _super.prototype.dispose.call(this);
  52375. };
  52376. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52377. if (!this._internalTextures) {
  52378. return;
  52379. }
  52380. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52381. if (this._internalTextures[i] !== undefined) {
  52382. this._internalTextures[i].dispose();
  52383. this._internalTextures.splice(i, 1);
  52384. }
  52385. }
  52386. };
  52387. return MultiRenderTarget;
  52388. }(BABYLON.RenderTargetTexture));
  52389. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52390. })(BABYLON || (BABYLON = {}));
  52391. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52392. var BABYLON;
  52393. (function (BABYLON) {
  52394. var MirrorTexture = /** @class */ (function (_super) {
  52395. __extends(MirrorTexture, _super);
  52396. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52397. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52399. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52400. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52401. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52402. _this._transformMatrix = BABYLON.Matrix.Zero();
  52403. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52404. _this._adaptiveBlurKernel = 0;
  52405. _this._blurKernelX = 0;
  52406. _this._blurKernelY = 0;
  52407. _this._blurRatio = 1.0;
  52408. _this.ignoreCameraViewport = true;
  52409. _this.onBeforeRenderObservable.add(function () {
  52410. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52411. _this._savedViewMatrix = scene.getViewMatrix();
  52412. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52413. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52414. scene.clipPlane = _this.mirrorPlane;
  52415. scene.getEngine().cullBackFaces = false;
  52416. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52417. });
  52418. _this.onAfterRenderObservable.add(function () {
  52419. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52420. scene.getEngine().cullBackFaces = true;
  52421. scene._mirroredCameraPosition = null;
  52422. delete scene.clipPlane;
  52423. });
  52424. return _this;
  52425. }
  52426. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52427. get: function () {
  52428. return this._blurRatio;
  52429. },
  52430. set: function (value) {
  52431. if (this._blurRatio === value) {
  52432. return;
  52433. }
  52434. this._blurRatio = value;
  52435. this._preparePostProcesses();
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52441. set: function (value) {
  52442. this._adaptiveBlurKernel = value;
  52443. this._autoComputeBlurKernel();
  52444. },
  52445. enumerable: true,
  52446. configurable: true
  52447. });
  52448. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52449. set: function (value) {
  52450. this.blurKernelX = value;
  52451. this.blurKernelY = value;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52457. get: function () {
  52458. return this._blurKernelX;
  52459. },
  52460. set: function (value) {
  52461. if (this._blurKernelX === value) {
  52462. return;
  52463. }
  52464. this._blurKernelX = value;
  52465. this._preparePostProcesses();
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52471. get: function () {
  52472. return this._blurKernelY;
  52473. },
  52474. set: function (value) {
  52475. if (this._blurKernelY === value) {
  52476. return;
  52477. }
  52478. this._blurKernelY = value;
  52479. this._preparePostProcesses();
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52485. var engine = this.getScene().getEngine();
  52486. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52487. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52488. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52489. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52490. };
  52491. MirrorTexture.prototype._onRatioRescale = function () {
  52492. if (this._sizeRatio) {
  52493. this.resize(this._initialSizeParameter);
  52494. if (!this._adaptiveBlurKernel) {
  52495. this._preparePostProcesses();
  52496. }
  52497. }
  52498. if (this._adaptiveBlurKernel) {
  52499. this._autoComputeBlurKernel();
  52500. }
  52501. };
  52502. MirrorTexture.prototype._preparePostProcesses = function () {
  52503. this.clearPostProcesses(true);
  52504. if (this._blurKernelX && this._blurKernelY) {
  52505. var engine = this.getScene().getEngine();
  52506. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52507. 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);
  52508. this._blurX.autoClear = false;
  52509. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52510. this._blurX.outputTexture = this._texture;
  52511. }
  52512. else {
  52513. this._blurX.alwaysForcePOT = true;
  52514. }
  52515. 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);
  52516. this._blurY.autoClear = false;
  52517. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52518. this.addPostProcess(this._blurX);
  52519. this.addPostProcess(this._blurY);
  52520. }
  52521. else {
  52522. if (this._blurY) {
  52523. this.removePostProcess(this._blurY);
  52524. this._blurY.dispose();
  52525. this._blurY = null;
  52526. }
  52527. if (this._blurX) {
  52528. this.removePostProcess(this._blurX);
  52529. this._blurX.dispose();
  52530. this._blurX = null;
  52531. }
  52532. }
  52533. };
  52534. MirrorTexture.prototype.clone = function () {
  52535. var scene = this.getScene();
  52536. if (!scene) {
  52537. return this;
  52538. }
  52539. var textureSize = this.getSize();
  52540. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52541. // Base texture
  52542. newTexture.hasAlpha = this.hasAlpha;
  52543. newTexture.level = this.level;
  52544. // Mirror Texture
  52545. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52546. if (this.renderList) {
  52547. newTexture.renderList = this.renderList.slice(0);
  52548. }
  52549. return newTexture;
  52550. };
  52551. MirrorTexture.prototype.serialize = function () {
  52552. if (!this.name) {
  52553. return null;
  52554. }
  52555. var serializationObject = _super.prototype.serialize.call(this);
  52556. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52557. return serializationObject;
  52558. };
  52559. return MirrorTexture;
  52560. }(BABYLON.RenderTargetTexture));
  52561. BABYLON.MirrorTexture = MirrorTexture;
  52562. })(BABYLON || (BABYLON = {}));
  52563. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52564. var BABYLON;
  52565. (function (BABYLON) {
  52566. /**
  52567. * Creates a refraction texture used by refraction channel of the standard material.
  52568. * @param name the texture name
  52569. * @param size size of the underlying texture
  52570. * @param scene root scene
  52571. */
  52572. var RefractionTexture = /** @class */ (function (_super) {
  52573. __extends(RefractionTexture, _super);
  52574. function RefractionTexture(name, size, scene, generateMipMaps) {
  52575. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52576. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52577. _this.depth = 2.0;
  52578. _this.onBeforeRenderObservable.add(function () {
  52579. scene.clipPlane = _this.refractionPlane;
  52580. });
  52581. _this.onAfterRenderObservable.add(function () {
  52582. delete scene.clipPlane;
  52583. });
  52584. return _this;
  52585. }
  52586. RefractionTexture.prototype.clone = function () {
  52587. var scene = this.getScene();
  52588. if (!scene) {
  52589. return this;
  52590. }
  52591. var textureSize = this.getSize();
  52592. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52593. // Base texture
  52594. newTexture.hasAlpha = this.hasAlpha;
  52595. newTexture.level = this.level;
  52596. // Refraction Texture
  52597. newTexture.refractionPlane = this.refractionPlane.clone();
  52598. if (this.renderList) {
  52599. newTexture.renderList = this.renderList.slice(0);
  52600. }
  52601. newTexture.depth = this.depth;
  52602. return newTexture;
  52603. };
  52604. RefractionTexture.prototype.serialize = function () {
  52605. if (!this.name) {
  52606. return null;
  52607. }
  52608. var serializationObject = _super.prototype.serialize.call(this);
  52609. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52610. serializationObject.depth = this.depth;
  52611. return serializationObject;
  52612. };
  52613. return RefractionTexture;
  52614. }(BABYLON.RenderTargetTexture));
  52615. BABYLON.RefractionTexture = RefractionTexture;
  52616. })(BABYLON || (BABYLON = {}));
  52617. //# sourceMappingURL=babylon.refractionTexture.js.map
  52618. var BABYLON;
  52619. (function (BABYLON) {
  52620. var DynamicTexture = /** @class */ (function (_super) {
  52621. __extends(DynamicTexture, _super);
  52622. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52623. if (scene === void 0) { scene = null; }
  52624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52625. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52626. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52627. _this.name = name;
  52628. _this._engine = _this.getScene().getEngine();
  52629. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52630. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52631. _this._generateMipMaps = generateMipMaps;
  52632. if (options.getContext) {
  52633. _this._canvas = options;
  52634. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52635. }
  52636. else {
  52637. _this._canvas = document.createElement("canvas");
  52638. if (options.width) {
  52639. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52640. }
  52641. else {
  52642. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52643. }
  52644. }
  52645. var textureSize = _this.getSize();
  52646. _this._canvas.width = textureSize.width;
  52647. _this._canvas.height = textureSize.height;
  52648. _this._context = _this._canvas.getContext("2d");
  52649. return _this;
  52650. }
  52651. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52652. get: function () {
  52653. return true;
  52654. },
  52655. enumerable: true,
  52656. configurable: true
  52657. });
  52658. DynamicTexture.prototype._recreate = function (textureSize) {
  52659. this._canvas.width = textureSize.width;
  52660. this._canvas.height = textureSize.height;
  52661. this.releaseInternalTexture();
  52662. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52663. };
  52664. DynamicTexture.prototype.scale = function (ratio) {
  52665. var textureSize = this.getSize();
  52666. textureSize.width *= ratio;
  52667. textureSize.height *= ratio;
  52668. this._recreate(textureSize);
  52669. };
  52670. DynamicTexture.prototype.scaleTo = function (width, height) {
  52671. var textureSize = this.getSize();
  52672. textureSize.width = width;
  52673. textureSize.height = height;
  52674. this._recreate(textureSize);
  52675. };
  52676. DynamicTexture.prototype.getContext = function () {
  52677. return this._context;
  52678. };
  52679. DynamicTexture.prototype.clear = function () {
  52680. var size = this.getSize();
  52681. this._context.fillRect(0, 0, size.width, size.height);
  52682. };
  52683. DynamicTexture.prototype.update = function (invertY) {
  52684. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52685. };
  52686. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52687. if (update === void 0) { update = true; }
  52688. var size = this.getSize();
  52689. if (clearColor) {
  52690. this._context.fillStyle = clearColor;
  52691. this._context.fillRect(0, 0, size.width, size.height);
  52692. }
  52693. this._context.font = font;
  52694. if (x === null || x === undefined) {
  52695. var textSize = this._context.measureText(text);
  52696. x = (size.width - textSize.width) / 2;
  52697. }
  52698. if (y === null || y === undefined) {
  52699. var fontSize = parseInt((font.replace(/\D/g, '')));
  52700. ;
  52701. y = (size.height / 2) + (fontSize / 3.65);
  52702. }
  52703. this._context.fillStyle = color;
  52704. this._context.fillText(text, x, y);
  52705. if (update) {
  52706. this.update(invertY);
  52707. }
  52708. };
  52709. DynamicTexture.prototype.clone = function () {
  52710. var scene = this.getScene();
  52711. if (!scene) {
  52712. return this;
  52713. }
  52714. var textureSize = this.getSize();
  52715. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52716. // Base texture
  52717. newTexture.hasAlpha = this.hasAlpha;
  52718. newTexture.level = this.level;
  52719. // Dynamic Texture
  52720. newTexture.wrapU = this.wrapU;
  52721. newTexture.wrapV = this.wrapV;
  52722. return newTexture;
  52723. };
  52724. DynamicTexture.prototype._rebuild = function () {
  52725. this.update();
  52726. };
  52727. return DynamicTexture;
  52728. }(BABYLON.Texture));
  52729. BABYLON.DynamicTexture = DynamicTexture;
  52730. })(BABYLON || (BABYLON = {}));
  52731. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52732. var BABYLON;
  52733. (function (BABYLON) {
  52734. var VideoTexture = /** @class */ (function (_super) {
  52735. __extends(VideoTexture, _super);
  52736. /**
  52737. * Creates a video texture.
  52738. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52739. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52740. * @param {BABYLON.Scene} scene is obviously the current scene.
  52741. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52742. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52743. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52744. */
  52745. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52746. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52747. if (invertY === void 0) { invertY = false; }
  52748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52749. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52750. _this._autoLaunch = true;
  52751. var urls = null;
  52752. _this.name = name;
  52753. if (urlsOrVideo instanceof HTMLVideoElement) {
  52754. _this.video = urlsOrVideo;
  52755. }
  52756. else {
  52757. urls = urlsOrVideo;
  52758. _this.video = document.createElement("video");
  52759. _this.video.autoplay = false;
  52760. _this.video.loop = true;
  52761. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52762. }
  52763. _this._engine = _this.getScene().getEngine();
  52764. _this._generateMipMaps = generateMipMaps;
  52765. _this._samplingMode = samplingMode;
  52766. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52767. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52768. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52769. }
  52770. else {
  52771. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52772. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52773. _this._generateMipMaps = false;
  52774. }
  52775. if (urls) {
  52776. _this.video.addEventListener("canplay", function () {
  52777. if (_this._texture === undefined) {
  52778. _this._createTexture();
  52779. }
  52780. });
  52781. urls.forEach(function (url) {
  52782. var source = document.createElement("source");
  52783. source.src = url;
  52784. _this.video.appendChild(source);
  52785. });
  52786. }
  52787. else {
  52788. _this._createTexture();
  52789. }
  52790. _this._lastUpdate = BABYLON.Tools.Now;
  52791. return _this;
  52792. }
  52793. VideoTexture.prototype.__setTextureReady = function () {
  52794. if (this._texture) {
  52795. this._texture.isReady = true;
  52796. }
  52797. };
  52798. VideoTexture.prototype._createTexture = function () {
  52799. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52800. if (this._autoLaunch) {
  52801. this._autoLaunch = false;
  52802. this.video.play();
  52803. }
  52804. this._setTextureReady = this.__setTextureReady.bind(this);
  52805. this.video.addEventListener("playing", this._setTextureReady);
  52806. };
  52807. VideoTexture.prototype._rebuild = function () {
  52808. this.update();
  52809. };
  52810. VideoTexture.prototype.update = function () {
  52811. var now = BABYLON.Tools.Now;
  52812. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52813. return false;
  52814. }
  52815. this._lastUpdate = now;
  52816. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52817. return true;
  52818. };
  52819. VideoTexture.prototype.dispose = function () {
  52820. _super.prototype.dispose.call(this);
  52821. this.video.removeEventListener("playing", this._setTextureReady);
  52822. };
  52823. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52824. var video = document.createElement("video");
  52825. var constraintsDeviceId;
  52826. if (constraints && constraints.deviceId) {
  52827. constraintsDeviceId = {
  52828. exact: constraints.deviceId
  52829. };
  52830. }
  52831. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52832. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52833. if (navigator.getUserMedia) {
  52834. navigator.getUserMedia({
  52835. video: {
  52836. deviceId: constraintsDeviceId,
  52837. width: {
  52838. min: (constraints && constraints.minWidth) || 256,
  52839. max: (constraints && constraints.maxWidth) || 640
  52840. },
  52841. height: {
  52842. min: (constraints && constraints.minHeight) || 256,
  52843. max: (constraints && constraints.maxHeight) || 480
  52844. }
  52845. }
  52846. }, function (stream) {
  52847. if (video.mozSrcObject !== undefined) {
  52848. video.mozSrcObject = stream;
  52849. }
  52850. else {
  52851. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52852. }
  52853. video.play();
  52854. if (onReady) {
  52855. onReady(new VideoTexture("video", video, scene, true, true));
  52856. }
  52857. }, function (e) {
  52858. BABYLON.Tools.Error(e.name);
  52859. });
  52860. }
  52861. };
  52862. return VideoTexture;
  52863. }(BABYLON.Texture));
  52864. BABYLON.VideoTexture = VideoTexture;
  52865. })(BABYLON || (BABYLON = {}));
  52866. //# sourceMappingURL=babylon.videoTexture.js.map
  52867. var BABYLON;
  52868. (function (BABYLON) {
  52869. var RawTexture = /** @class */ (function (_super) {
  52870. __extends(RawTexture, _super);
  52871. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52873. if (invertY === void 0) { invertY = false; }
  52874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52875. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52876. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52877. _this.format = format;
  52878. _this._engine = scene.getEngine();
  52879. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52880. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52881. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52882. return _this;
  52883. }
  52884. RawTexture.prototype.update = function (data) {
  52885. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52886. };
  52887. // Statics
  52888. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52889. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52890. if (invertY === void 0) { invertY = false; }
  52891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52892. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52893. };
  52894. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52895. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52896. if (invertY === void 0) { invertY = false; }
  52897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52898. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52899. };
  52900. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52901. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52902. if (invertY === void 0) { invertY = false; }
  52903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52904. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52905. };
  52906. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52907. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52908. if (invertY === void 0) { invertY = false; }
  52909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52910. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52911. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52912. };
  52913. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52914. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52915. if (invertY === void 0) { invertY = false; }
  52916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52917. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52918. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52919. };
  52920. return RawTexture;
  52921. }(BABYLON.Texture));
  52922. BABYLON.RawTexture = RawTexture;
  52923. })(BABYLON || (BABYLON = {}));
  52924. //# sourceMappingURL=babylon.rawTexture.js.map
  52925. var BABYLON;
  52926. (function (BABYLON) {
  52927. var PostProcess = /** @class */ (function () {
  52928. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52930. if (defines === void 0) { defines = null; }
  52931. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52932. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52933. if (blockCompilation === void 0) { blockCompilation = false; }
  52934. this.name = name;
  52935. this.width = -1;
  52936. this.height = -1;
  52937. this.autoClear = true;
  52938. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52939. this.animations = new Array();
  52940. /*
  52941. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52942. Can only be used on a single postprocess or on the last one of a chain.
  52943. */
  52944. this.enablePixelPerfectMode = false;
  52945. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52946. this.alwaysForcePOT = false;
  52947. this.samples = 1;
  52948. this.adaptScaleToCurrentViewport = false;
  52949. this._reusable = false;
  52950. this._textures = new BABYLON.SmartArray(2);
  52951. this._currentRenderTextureInd = 0;
  52952. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52953. this._texelSize = BABYLON.Vector2.Zero();
  52954. // Events
  52955. /**
  52956. * An event triggered when the postprocess is activated.
  52957. * @type {BABYLON.Observable}
  52958. */
  52959. this.onActivateObservable = new BABYLON.Observable();
  52960. /**
  52961. * An event triggered when the postprocess changes its size.
  52962. * @type {BABYLON.Observable}
  52963. */
  52964. this.onSizeChangedObservable = new BABYLON.Observable();
  52965. /**
  52966. * An event triggered when the postprocess applies its effect.
  52967. * @type {BABYLON.Observable}
  52968. */
  52969. this.onApplyObservable = new BABYLON.Observable();
  52970. /**
  52971. * An event triggered before rendering the postprocess
  52972. * @type {BABYLON.Observable}
  52973. */
  52974. this.onBeforeRenderObservable = new BABYLON.Observable();
  52975. /**
  52976. * An event triggered after rendering the postprocess
  52977. * @type {BABYLON.Observable}
  52978. */
  52979. this.onAfterRenderObservable = new BABYLON.Observable();
  52980. if (camera != null) {
  52981. this._camera = camera;
  52982. this._scene = camera.getScene();
  52983. camera.attachPostProcess(this);
  52984. this._engine = this._scene.getEngine();
  52985. this._scene.postProcesses.push(this);
  52986. }
  52987. else if (engine) {
  52988. this._engine = engine;
  52989. this._engine.postProcesses.push(this);
  52990. }
  52991. this._options = options;
  52992. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52993. this._reusable = reusable || false;
  52994. this._textureType = textureType;
  52995. this._samplers = samplers || [];
  52996. this._samplers.push("textureSampler");
  52997. this._fragmentUrl = fragmentUrl;
  52998. this._vertexUrl = vertexUrl;
  52999. this._parameters = parameters || [];
  53000. this._parameters.push("scale");
  53001. this._indexParameters = indexParameters;
  53002. if (!blockCompilation) {
  53003. this.updateEffect(defines);
  53004. }
  53005. }
  53006. Object.defineProperty(PostProcess.prototype, "onActivate", {
  53007. set: function (callback) {
  53008. if (this._onActivateObserver) {
  53009. this.onActivateObservable.remove(this._onActivateObserver);
  53010. }
  53011. if (callback) {
  53012. this._onActivateObserver = this.onActivateObservable.add(callback);
  53013. }
  53014. },
  53015. enumerable: true,
  53016. configurable: true
  53017. });
  53018. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53019. set: function (callback) {
  53020. if (this._onSizeChangedObserver) {
  53021. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53022. }
  53023. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. Object.defineProperty(PostProcess.prototype, "onApply", {
  53029. set: function (callback) {
  53030. if (this._onApplyObserver) {
  53031. this.onApplyObservable.remove(this._onApplyObserver);
  53032. }
  53033. this._onApplyObserver = this.onApplyObservable.add(callback);
  53034. },
  53035. enumerable: true,
  53036. configurable: true
  53037. });
  53038. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53039. set: function (callback) {
  53040. if (this._onBeforeRenderObserver) {
  53041. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53042. }
  53043. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53044. },
  53045. enumerable: true,
  53046. configurable: true
  53047. });
  53048. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53049. set: function (callback) {
  53050. if (this._onAfterRenderObserver) {
  53051. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53052. }
  53053. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53054. },
  53055. enumerable: true,
  53056. configurable: true
  53057. });
  53058. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53059. get: function () {
  53060. return this._textures.data[this._currentRenderTextureInd];
  53061. },
  53062. set: function (value) {
  53063. this._forcedOutputTexture = value;
  53064. },
  53065. enumerable: true,
  53066. configurable: true
  53067. });
  53068. PostProcess.prototype.getCamera = function () {
  53069. return this._camera;
  53070. };
  53071. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53072. get: function () {
  53073. if (this._shareOutputWithPostProcess) {
  53074. return this._shareOutputWithPostProcess.texelSize;
  53075. }
  53076. if (this._forcedOutputTexture) {
  53077. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53078. }
  53079. return this._texelSize;
  53080. },
  53081. enumerable: true,
  53082. configurable: true
  53083. });
  53084. PostProcess.prototype.getEngine = function () {
  53085. return this._engine;
  53086. };
  53087. PostProcess.prototype.getEffect = function () {
  53088. return this._effect;
  53089. };
  53090. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53091. this._disposeTextures();
  53092. this._shareOutputWithPostProcess = postProcess;
  53093. return this;
  53094. };
  53095. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53096. if (defines === void 0) { defines = null; }
  53097. if (uniforms === void 0) { uniforms = null; }
  53098. if (samplers === void 0) { samplers = null; }
  53099. 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);
  53100. };
  53101. PostProcess.prototype.isReusable = function () {
  53102. return this._reusable;
  53103. };
  53104. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53105. PostProcess.prototype.markTextureDirty = function () {
  53106. this.width = -1;
  53107. };
  53108. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53109. var _this = this;
  53110. if (sourceTexture === void 0) { sourceTexture = null; }
  53111. camera = camera || this._camera;
  53112. var scene = camera.getScene();
  53113. var engine = scene.getEngine();
  53114. var maxSize = engine.getCaps().maxTextureSize;
  53115. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53116. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53117. var desiredWidth = (this._options.width || requiredWidth);
  53118. var desiredHeight = this._options.height || requiredHeight;
  53119. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53120. if (this.adaptScaleToCurrentViewport) {
  53121. var currentViewport = engine.currentViewport;
  53122. if (currentViewport) {
  53123. desiredWidth *= currentViewport.width;
  53124. desiredHeight *= currentViewport.height;
  53125. }
  53126. }
  53127. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53128. if (!this._options.width) {
  53129. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53130. }
  53131. if (!this._options.height) {
  53132. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53133. }
  53134. }
  53135. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53136. if (this._textures.length > 0) {
  53137. for (var i = 0; i < this._textures.length; i++) {
  53138. this._engine._releaseTexture(this._textures.data[i]);
  53139. }
  53140. this._textures.reset();
  53141. }
  53142. this.width = desiredWidth;
  53143. this.height = desiredHeight;
  53144. var textureSize = { width: this.width, height: this.height };
  53145. var textureOptions = {
  53146. generateMipMaps: false,
  53147. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53148. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53149. samplingMode: this.renderTargetSamplingMode,
  53150. type: this._textureType
  53151. };
  53152. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53153. if (this._reusable) {
  53154. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53155. }
  53156. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53157. this.onSizeChangedObservable.notifyObservers(this);
  53158. }
  53159. this._textures.forEach(function (texture) {
  53160. if (texture.samples !== _this.samples) {
  53161. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53162. }
  53163. });
  53164. }
  53165. var target;
  53166. if (this._shareOutputWithPostProcess) {
  53167. target = this._shareOutputWithPostProcess.outputTexture;
  53168. }
  53169. else if (this._forcedOutputTexture) {
  53170. target = this._forcedOutputTexture;
  53171. this.width = this._forcedOutputTexture.width;
  53172. this.height = this._forcedOutputTexture.height;
  53173. }
  53174. else {
  53175. target = this.outputTexture;
  53176. }
  53177. if (this.enablePixelPerfectMode) {
  53178. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53179. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53180. }
  53181. else {
  53182. this._scaleRatio.copyFromFloats(1, 1);
  53183. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53184. }
  53185. this.onActivateObservable.notifyObservers(camera);
  53186. // Clear
  53187. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53188. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53189. }
  53190. if (this._reusable) {
  53191. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53192. }
  53193. };
  53194. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53195. get: function () {
  53196. return this._effect.isSupported;
  53197. },
  53198. enumerable: true,
  53199. configurable: true
  53200. });
  53201. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53202. get: function () {
  53203. if (this._shareOutputWithPostProcess) {
  53204. return this._shareOutputWithPostProcess.aspectRatio;
  53205. }
  53206. if (this._forcedOutputTexture) {
  53207. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53208. }
  53209. return this.width / this.height;
  53210. },
  53211. enumerable: true,
  53212. configurable: true
  53213. });
  53214. /**
  53215. * Get a value indicating if the post-process is ready to be used
  53216. * @returns true if the post-process is ready (shader is compiled)
  53217. */
  53218. PostProcess.prototype.isReady = function () {
  53219. return this._effect && this._effect.isReady();
  53220. };
  53221. PostProcess.prototype.apply = function () {
  53222. // Check
  53223. if (!this._effect || !this._effect.isReady())
  53224. return null;
  53225. // States
  53226. this._engine.enableEffect(this._effect);
  53227. this._engine.setState(false);
  53228. this._engine.setDepthBuffer(false);
  53229. this._engine.setDepthWrite(false);
  53230. // Alpha
  53231. this._engine.setAlphaMode(this.alphaMode);
  53232. if (this.alphaConstants) {
  53233. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53234. }
  53235. // Texture
  53236. var source;
  53237. if (this._shareOutputWithPostProcess) {
  53238. source = this._shareOutputWithPostProcess.outputTexture;
  53239. }
  53240. else if (this._forcedOutputTexture) {
  53241. source = this._forcedOutputTexture;
  53242. }
  53243. else {
  53244. source = this.outputTexture;
  53245. }
  53246. this._effect._bindTexture("textureSampler", source);
  53247. // Parameters
  53248. this._effect.setVector2("scale", this._scaleRatio);
  53249. this.onApplyObservable.notifyObservers(this._effect);
  53250. return this._effect;
  53251. };
  53252. PostProcess.prototype._disposeTextures = function () {
  53253. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53254. return;
  53255. }
  53256. if (this._textures.length > 0) {
  53257. for (var i = 0; i < this._textures.length; i++) {
  53258. this._engine._releaseTexture(this._textures.data[i]);
  53259. }
  53260. }
  53261. this._textures.dispose();
  53262. };
  53263. PostProcess.prototype.dispose = function (camera) {
  53264. camera = camera || this._camera;
  53265. this._disposeTextures();
  53266. if (this._scene) {
  53267. var index_1 = this._scene.postProcesses.indexOf(this);
  53268. if (index_1 !== -1) {
  53269. this._scene.postProcesses.splice(index_1, 1);
  53270. }
  53271. }
  53272. else {
  53273. var index_2 = this._engine.postProcesses.indexOf(this);
  53274. if (index_2 !== -1) {
  53275. this._engine.postProcesses.splice(index_2, 1);
  53276. }
  53277. }
  53278. if (!camera) {
  53279. return;
  53280. }
  53281. camera.detachPostProcess(this);
  53282. var index = camera._postProcesses.indexOf(this);
  53283. if (index === 0 && camera._postProcesses.length > 0) {
  53284. this._camera._postProcesses[0].markTextureDirty();
  53285. }
  53286. this.onActivateObservable.clear();
  53287. this.onAfterRenderObservable.clear();
  53288. this.onApplyObservable.clear();
  53289. this.onBeforeRenderObservable.clear();
  53290. this.onSizeChangedObservable.clear();
  53291. };
  53292. return PostProcess;
  53293. }());
  53294. BABYLON.PostProcess = PostProcess;
  53295. })(BABYLON || (BABYLON = {}));
  53296. //# sourceMappingURL=babylon.postProcess.js.map
  53297. var BABYLON;
  53298. (function (BABYLON) {
  53299. var PassPostProcess = /** @class */ (function (_super) {
  53300. __extends(PassPostProcess, _super);
  53301. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53302. if (camera === void 0) { camera = null; }
  53303. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53304. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53305. }
  53306. return PassPostProcess;
  53307. }(BABYLON.PostProcess));
  53308. BABYLON.PassPostProcess = PassPostProcess;
  53309. })(BABYLON || (BABYLON = {}));
  53310. //# sourceMappingURL=babylon.passPostProcess.js.map
  53311. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53312. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53313. s = arguments[i];
  53314. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53315. t[p] = s[p];
  53316. }
  53317. return t;
  53318. };
  53319. var BABYLON;
  53320. (function (BABYLON) {
  53321. var ShadowGenerator = /** @class */ (function () {
  53322. /**
  53323. * Creates a ShadowGenerator object.
  53324. * A ShadowGenerator is the required tool to use the shadows.
  53325. * Each light casting shadows needs to use its own ShadowGenerator.
  53326. * Required parameters :
  53327. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53328. * - `light`: the light object generating the shadows.
  53329. * - `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.
  53330. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53331. */
  53332. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53333. // Members
  53334. this._bias = 0.00005;
  53335. this._blurBoxOffset = 1;
  53336. this._blurScale = 2;
  53337. this._blurKernel = 1;
  53338. this._useKernelBlur = false;
  53339. this._filter = ShadowGenerator.FILTER_NONE;
  53340. this._darkness = 0;
  53341. this._transparencyShadow = false;
  53342. /**
  53343. * Controls the extent to which the shadows fade out at the edge of the frustum
  53344. * Used only by directionals and spots
  53345. */
  53346. this.frustumEdgeFalloff = 0;
  53347. this.forceBackFacesOnly = false;
  53348. this._lightDirection = BABYLON.Vector3.Zero();
  53349. this._viewMatrix = BABYLON.Matrix.Zero();
  53350. this._projectionMatrix = BABYLON.Matrix.Zero();
  53351. this._transformMatrix = BABYLON.Matrix.Zero();
  53352. this._currentFaceIndex = 0;
  53353. this._currentFaceIndexCache = 0;
  53354. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53355. this._mapSize = mapSize;
  53356. this._light = light;
  53357. this._scene = light.getScene();
  53358. light._shadowGenerator = this;
  53359. // Texture type fallback from float to int if not supported.
  53360. var caps = this._scene.getEngine().getCaps();
  53361. if (!useFullFloatFirst) {
  53362. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53363. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53364. }
  53365. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53366. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53367. }
  53368. else {
  53369. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53370. }
  53371. }
  53372. else {
  53373. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53374. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53375. }
  53376. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53377. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53378. }
  53379. else {
  53380. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53381. }
  53382. }
  53383. this._initializeGenerator();
  53384. }
  53385. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53386. // Static
  53387. get: function () {
  53388. return ShadowGenerator._FILTER_NONE;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53394. get: function () {
  53395. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53396. },
  53397. enumerable: true,
  53398. configurable: true
  53399. });
  53400. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53401. get: function () {
  53402. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53408. get: function () {
  53409. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53410. },
  53411. enumerable: true,
  53412. configurable: true
  53413. });
  53414. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53415. get: function () {
  53416. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53422. get: function () {
  53423. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53429. get: function () {
  53430. return this._bias;
  53431. },
  53432. set: function (bias) {
  53433. this._bias = bias;
  53434. },
  53435. enumerable: true,
  53436. configurable: true
  53437. });
  53438. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53439. get: function () {
  53440. return this._blurBoxOffset;
  53441. },
  53442. set: function (value) {
  53443. if (this._blurBoxOffset === value) {
  53444. return;
  53445. }
  53446. this._blurBoxOffset = value;
  53447. this._disposeBlurPostProcesses();
  53448. },
  53449. enumerable: true,
  53450. configurable: true
  53451. });
  53452. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53453. get: function () {
  53454. return this._blurScale;
  53455. },
  53456. set: function (value) {
  53457. if (this._blurScale === value) {
  53458. return;
  53459. }
  53460. this._blurScale = value;
  53461. this._disposeBlurPostProcesses();
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53467. get: function () {
  53468. return this._blurKernel;
  53469. },
  53470. set: function (value) {
  53471. if (this._blurKernel === value) {
  53472. return;
  53473. }
  53474. this._blurKernel = value;
  53475. this._disposeBlurPostProcesses();
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53481. get: function () {
  53482. return this._useKernelBlur;
  53483. },
  53484. set: function (value) {
  53485. if (this._useKernelBlur === value) {
  53486. return;
  53487. }
  53488. this._useKernelBlur = value;
  53489. this._disposeBlurPostProcesses();
  53490. },
  53491. enumerable: true,
  53492. configurable: true
  53493. });
  53494. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53495. get: function () {
  53496. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53497. },
  53498. set: function (value) {
  53499. this._depthScale = value;
  53500. },
  53501. enumerable: true,
  53502. configurable: true
  53503. });
  53504. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53505. get: function () {
  53506. return this._filter;
  53507. },
  53508. set: function (value) {
  53509. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53510. if (this._light.needCube()) {
  53511. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53512. this.useExponentialShadowMap = true;
  53513. return;
  53514. }
  53515. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53516. this.useCloseExponentialShadowMap = true;
  53517. return;
  53518. }
  53519. }
  53520. if (this._filter === value) {
  53521. return;
  53522. }
  53523. this._filter = value;
  53524. this._disposeBlurPostProcesses();
  53525. this._applyFilterValues();
  53526. this._light._markMeshesAsLightDirty();
  53527. },
  53528. enumerable: true,
  53529. configurable: true
  53530. });
  53531. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53532. get: function () {
  53533. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53534. },
  53535. set: function (value) {
  53536. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53537. return;
  53538. }
  53539. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53540. },
  53541. enumerable: true,
  53542. configurable: true
  53543. });
  53544. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53545. get: function () {
  53546. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53547. return this.useExponentialShadowMap;
  53548. },
  53549. set: function (value) {
  53550. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53551. this.useExponentialShadowMap = value;
  53552. },
  53553. enumerable: true,
  53554. configurable: true
  53555. });
  53556. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53557. get: function () {
  53558. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53559. return this.useBlurExponentialShadowMap;
  53560. },
  53561. set: function (value) {
  53562. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53563. this.useBlurExponentialShadowMap = value;
  53564. },
  53565. enumerable: true,
  53566. configurable: true
  53567. });
  53568. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53569. get: function () {
  53570. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53571. },
  53572. set: function (value) {
  53573. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53574. return;
  53575. }
  53576. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53577. },
  53578. enumerable: true,
  53579. configurable: true
  53580. });
  53581. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53582. get: function () {
  53583. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53584. },
  53585. set: function (value) {
  53586. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53587. return;
  53588. }
  53589. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53590. },
  53591. enumerable: true,
  53592. configurable: true
  53593. });
  53594. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53595. get: function () {
  53596. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53597. },
  53598. set: function (value) {
  53599. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53600. return;
  53601. }
  53602. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53603. },
  53604. enumerable: true,
  53605. configurable: true
  53606. });
  53607. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53608. get: function () {
  53609. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53610. },
  53611. set: function (value) {
  53612. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53613. return;
  53614. }
  53615. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53616. },
  53617. enumerable: true,
  53618. configurable: true
  53619. });
  53620. /**
  53621. * Returns the darkness value (float).
  53622. */
  53623. ShadowGenerator.prototype.getDarkness = function () {
  53624. return this._darkness;
  53625. };
  53626. /**
  53627. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53628. * Returns the ShadowGenerator.
  53629. */
  53630. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53631. if (darkness >= 1.0)
  53632. this._darkness = 1.0;
  53633. else if (darkness <= 0.0)
  53634. this._darkness = 0.0;
  53635. else
  53636. this._darkness = darkness;
  53637. return this;
  53638. };
  53639. /**
  53640. * Sets the ability to have transparent shadow (boolean).
  53641. * Returns the ShadowGenerator.
  53642. */
  53643. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53644. this._transparencyShadow = hasShadow;
  53645. return this;
  53646. };
  53647. /**
  53648. * Returns a RenderTargetTexture object : the shadow map texture.
  53649. */
  53650. ShadowGenerator.prototype.getShadowMap = function () {
  53651. return this._shadowMap;
  53652. };
  53653. /**
  53654. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53655. */
  53656. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53657. if (this._shadowMap2) {
  53658. return this._shadowMap2;
  53659. }
  53660. return this._shadowMap;
  53661. };
  53662. /**
  53663. * Helper function to add a mesh and its descendants to the list of shadow casters
  53664. * @param mesh Mesh to add
  53665. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53666. */
  53667. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53668. if (includeDescendants === void 0) { includeDescendants = true; }
  53669. if (!this._shadowMap) {
  53670. return this;
  53671. }
  53672. if (!this._shadowMap.renderList) {
  53673. this._shadowMap.renderList = [];
  53674. }
  53675. this._shadowMap.renderList.push(mesh);
  53676. if (includeDescendants) {
  53677. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53678. }
  53679. return this;
  53680. var _a;
  53681. };
  53682. /**
  53683. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53684. * @param mesh Mesh to remove
  53685. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53686. */
  53687. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53688. if (includeDescendants === void 0) { includeDescendants = true; }
  53689. if (!this._shadowMap || !this._shadowMap.renderList) {
  53690. return this;
  53691. }
  53692. var index = this._shadowMap.renderList.indexOf(mesh);
  53693. if (index !== -1) {
  53694. this._shadowMap.renderList.splice(index, 1);
  53695. }
  53696. if (includeDescendants) {
  53697. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53698. var child = _a[_i];
  53699. this.removeShadowCaster(child);
  53700. }
  53701. }
  53702. return this;
  53703. };
  53704. /**
  53705. * Returns the associated light object.
  53706. */
  53707. ShadowGenerator.prototype.getLight = function () {
  53708. return this._light;
  53709. };
  53710. ShadowGenerator.prototype._initializeGenerator = function () {
  53711. this._light._markMeshesAsLightDirty();
  53712. this._initializeShadowMap();
  53713. };
  53714. ShadowGenerator.prototype._initializeShadowMap = function () {
  53715. var _this = this;
  53716. // Render target
  53717. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53718. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53719. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53720. this._shadowMap.anisotropicFilteringLevel = 1;
  53721. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53722. this._shadowMap.renderParticles = false;
  53723. this._shadowMap.ignoreCameraViewport = true;
  53724. // Record Face Index before render.
  53725. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53726. _this._currentFaceIndex = faceIndex;
  53727. });
  53728. // Custom render function.
  53729. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53730. // Blur if required afer render.
  53731. this._shadowMap.onAfterUnbindObservable.add(function () {
  53732. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53733. return;
  53734. }
  53735. var shadowMap = _this.getShadowMapForRendering();
  53736. if (shadowMap) {
  53737. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53738. }
  53739. });
  53740. // Clear according to the chosen filter.
  53741. this._shadowMap.onClearObservable.add(function (engine) {
  53742. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53743. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53744. }
  53745. else {
  53746. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53747. }
  53748. });
  53749. };
  53750. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53751. var _this = this;
  53752. var engine = this._scene.getEngine();
  53753. var targetSize = this._mapSize / this.blurScale;
  53754. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53755. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53756. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53757. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53758. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53759. }
  53760. if (this.useKernelBlur) {
  53761. 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);
  53762. this._kernelBlurXPostprocess.width = targetSize;
  53763. this._kernelBlurXPostprocess.height = targetSize;
  53764. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53765. effect.setTexture("textureSampler", _this._shadowMap);
  53766. });
  53767. 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);
  53768. this._kernelBlurXPostprocess.autoClear = false;
  53769. this._kernelBlurYPostprocess.autoClear = false;
  53770. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53771. this._kernelBlurXPostprocess.packedFloat = true;
  53772. this._kernelBlurYPostprocess.packedFloat = true;
  53773. }
  53774. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53775. }
  53776. else {
  53777. 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);
  53778. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53779. effect.setFloat2("screenSize", targetSize, targetSize);
  53780. effect.setTexture("textureSampler", _this._shadowMap);
  53781. });
  53782. this._boxBlurPostprocess.autoClear = false;
  53783. this._blurPostProcesses = [this._boxBlurPostprocess];
  53784. }
  53785. };
  53786. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53787. var index;
  53788. var engine = this._scene.getEngine();
  53789. if (depthOnlySubMeshes.length) {
  53790. engine.setColorWrite(false);
  53791. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53792. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53793. }
  53794. engine.setColorWrite(true);
  53795. }
  53796. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53797. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53798. }
  53799. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53800. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53801. }
  53802. if (this._transparencyShadow) {
  53803. for (index = 0; index < transparentSubMeshes.length; index++) {
  53804. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53805. }
  53806. }
  53807. };
  53808. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53809. var _this = this;
  53810. var mesh = subMesh.getRenderingMesh();
  53811. var scene = this._scene;
  53812. var engine = scene.getEngine();
  53813. var material = subMesh.getMaterial();
  53814. if (!material) {
  53815. return;
  53816. }
  53817. // Culling
  53818. engine.setState(material.backFaceCulling);
  53819. // Managing instances
  53820. var batch = mesh._getInstancesRenderList(subMesh._id);
  53821. if (batch.mustReturn) {
  53822. return;
  53823. }
  53824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53825. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53826. engine.enableEffect(this._effect);
  53827. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53828. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53829. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53830. this._effect.setVector3("lightPosition", this.getLight().position);
  53831. if (scene.activeCamera) {
  53832. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53833. }
  53834. // Alpha test
  53835. if (material && material.needAlphaTesting()) {
  53836. var alphaTexture = material.getAlphaTestTexture();
  53837. if (alphaTexture) {
  53838. this._effect.setTexture("diffuseSampler", alphaTexture);
  53839. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53840. }
  53841. }
  53842. // Bones
  53843. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53844. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53845. }
  53846. if (this.forceBackFacesOnly) {
  53847. engine.setState(true, 0, false, true);
  53848. }
  53849. // Draw
  53850. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53851. if (this.forceBackFacesOnly) {
  53852. engine.setState(true, 0, false, false);
  53853. }
  53854. }
  53855. else {
  53856. // Need to reset refresh rate of the shadowMap
  53857. if (this._shadowMap) {
  53858. this._shadowMap.resetRefreshCounter();
  53859. }
  53860. }
  53861. };
  53862. ShadowGenerator.prototype._applyFilterValues = function () {
  53863. if (!this._shadowMap) {
  53864. return;
  53865. }
  53866. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53867. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53868. }
  53869. else {
  53870. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53871. }
  53872. };
  53873. /**
  53874. * Force shader compilation including textures ready check
  53875. */
  53876. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53877. var _this = this;
  53878. var localOptions = __assign({ useInstances: false }, options);
  53879. var shadowMap = this.getShadowMap();
  53880. if (!shadowMap) {
  53881. if (onCompiled) {
  53882. onCompiled(this);
  53883. }
  53884. return;
  53885. }
  53886. var renderList = shadowMap.renderList;
  53887. if (!renderList) {
  53888. if (onCompiled) {
  53889. onCompiled(this);
  53890. }
  53891. return;
  53892. }
  53893. var subMeshes = new Array();
  53894. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53895. var mesh = renderList_1[_i];
  53896. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53897. }
  53898. if (subMeshes.length === 0) {
  53899. if (onCompiled) {
  53900. onCompiled(this);
  53901. }
  53902. return;
  53903. }
  53904. var currentIndex = 0;
  53905. var checkReady = function () {
  53906. if (!_this._scene || !_this._scene.getEngine()) {
  53907. return;
  53908. }
  53909. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53910. currentIndex++;
  53911. if (currentIndex >= subMeshes.length) {
  53912. if (onCompiled) {
  53913. onCompiled(_this);
  53914. }
  53915. return;
  53916. }
  53917. }
  53918. setTimeout(checkReady, 16);
  53919. };
  53920. checkReady();
  53921. };
  53922. /**
  53923. * Boolean : true when the ShadowGenerator is finally computed.
  53924. */
  53925. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53926. var defines = [];
  53927. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53928. defines.push("#define FLOAT");
  53929. }
  53930. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53931. defines.push("#define ESM");
  53932. }
  53933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53934. var mesh = subMesh.getMesh();
  53935. var material = subMesh.getMaterial();
  53936. // Alpha test
  53937. if (material && material.needAlphaTesting()) {
  53938. var alphaTexture = material.getAlphaTestTexture();
  53939. if (alphaTexture) {
  53940. defines.push("#define ALPHATEST");
  53941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53942. attribs.push(BABYLON.VertexBuffer.UVKind);
  53943. defines.push("#define UV1");
  53944. }
  53945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53946. if (alphaTexture.coordinatesIndex === 1) {
  53947. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53948. defines.push("#define UV2");
  53949. }
  53950. }
  53951. }
  53952. }
  53953. // Bones
  53954. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53957. if (mesh.numBoneInfluencers > 4) {
  53958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53960. }
  53961. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53962. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53963. }
  53964. else {
  53965. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53966. }
  53967. // Instances
  53968. if (useInstances) {
  53969. defines.push("#define INSTANCES");
  53970. attribs.push("world0");
  53971. attribs.push("world1");
  53972. attribs.push("world2");
  53973. attribs.push("world3");
  53974. }
  53975. // Get correct effect
  53976. var join = defines.join("\n");
  53977. if (this._cachedDefines !== join) {
  53978. this._cachedDefines = join;
  53979. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53980. }
  53981. if (!this._effect.isReady()) {
  53982. return false;
  53983. }
  53984. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53985. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  53986. this._initializeBlurRTTAndPostProcesses();
  53987. }
  53988. }
  53989. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  53990. return false;
  53991. }
  53992. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  53993. return false;
  53994. }
  53995. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  53996. return false;
  53997. }
  53998. return true;
  53999. };
  54000. /**
  54001. * This creates the defines related to the standard BJS materials.
  54002. */
  54003. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  54004. var scene = this._scene;
  54005. var light = this._light;
  54006. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54007. return;
  54008. }
  54009. defines["SHADOW" + lightIndex] = true;
  54010. if (this.usePoissonSampling) {
  54011. defines["SHADOWPCF" + lightIndex] = true;
  54012. }
  54013. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54014. defines["SHADOWESM" + lightIndex] = true;
  54015. }
  54016. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54017. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54018. }
  54019. if (light.needCube()) {
  54020. defines["SHADOWCUBE" + lightIndex] = true;
  54021. }
  54022. };
  54023. /**
  54024. * This binds shadow lights related to the standard BJS materials.
  54025. * It implies the unifroms available on the materials are the standard BJS ones.
  54026. */
  54027. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54028. var light = this._light;
  54029. var scene = this._scene;
  54030. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54031. return;
  54032. }
  54033. var camera = scene.activeCamera;
  54034. if (!camera) {
  54035. return;
  54036. }
  54037. var shadowMap = this.getShadowMap();
  54038. if (!shadowMap) {
  54039. return;
  54040. }
  54041. if (!light.needCube()) {
  54042. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54043. }
  54044. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54045. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54046. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54047. };
  54048. // Methods
  54049. /**
  54050. * Returns a Matrix object : the updated transformation matrix.
  54051. */
  54052. ShadowGenerator.prototype.getTransformMatrix = function () {
  54053. var scene = this._scene;
  54054. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54055. return this._transformMatrix;
  54056. }
  54057. this._currentRenderID = scene.getRenderId();
  54058. this._currentFaceIndexCache = this._currentFaceIndex;
  54059. var lightPosition = this._light.position;
  54060. if (this._light.computeTransformedInformation()) {
  54061. lightPosition = this._light.transformedPosition;
  54062. }
  54063. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54064. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54065. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54066. }
  54067. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54068. this._cachedPosition = lightPosition.clone();
  54069. this._cachedDirection = this._lightDirection.clone();
  54070. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54071. var shadowMap = this.getShadowMap();
  54072. if (shadowMap) {
  54073. var renderList = shadowMap.renderList;
  54074. if (renderList) {
  54075. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54076. }
  54077. }
  54078. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54079. }
  54080. return this._transformMatrix;
  54081. };
  54082. ShadowGenerator.prototype.recreateShadowMap = function () {
  54083. var shadowMap = this._shadowMap;
  54084. if (!shadowMap) {
  54085. return;
  54086. }
  54087. // Track render list.
  54088. var renderList = shadowMap.renderList;
  54089. // Clean up existing data.
  54090. this._disposeRTTandPostProcesses();
  54091. // Reinitializes.
  54092. this._initializeGenerator();
  54093. // Reaffect the filter to ensure a correct fallback if necessary.
  54094. this.filter = this.filter;
  54095. // Reaffect the filter.
  54096. this._applyFilterValues();
  54097. // Reaffect Render List.
  54098. this._shadowMap.renderList = renderList;
  54099. };
  54100. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54101. if (this._shadowMap2) {
  54102. this._shadowMap2.dispose();
  54103. this._shadowMap2 = null;
  54104. }
  54105. if (this._boxBlurPostprocess) {
  54106. this._boxBlurPostprocess.dispose();
  54107. this._boxBlurPostprocess = null;
  54108. }
  54109. if (this._kernelBlurXPostprocess) {
  54110. this._kernelBlurXPostprocess.dispose();
  54111. this._kernelBlurXPostprocess = null;
  54112. }
  54113. if (this._kernelBlurYPostprocess) {
  54114. this._kernelBlurYPostprocess.dispose();
  54115. this._kernelBlurYPostprocess = null;
  54116. }
  54117. this._blurPostProcesses = [];
  54118. };
  54119. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54120. if (this._shadowMap) {
  54121. this._shadowMap.dispose();
  54122. this._shadowMap = null;
  54123. }
  54124. this._disposeBlurPostProcesses();
  54125. };
  54126. /**
  54127. * Disposes the ShadowGenerator.
  54128. * Returns nothing.
  54129. */
  54130. ShadowGenerator.prototype.dispose = function () {
  54131. this._disposeRTTandPostProcesses();
  54132. if (this._light) {
  54133. this._light._shadowGenerator = null;
  54134. this._light._markMeshesAsLightDirty();
  54135. }
  54136. };
  54137. /**
  54138. * Serializes the ShadowGenerator and returns a serializationObject.
  54139. */
  54140. ShadowGenerator.prototype.serialize = function () {
  54141. var serializationObject = {};
  54142. var shadowMap = this.getShadowMap();
  54143. if (!shadowMap) {
  54144. return serializationObject;
  54145. }
  54146. serializationObject.lightId = this._light.id;
  54147. serializationObject.mapSize = shadowMap.getRenderSize();
  54148. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54149. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54150. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54151. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54152. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54153. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54154. serializationObject.depthScale = this.depthScale;
  54155. serializationObject.darkness = this.getDarkness();
  54156. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54157. serializationObject.blurKernel = this.blurKernel;
  54158. serializationObject.blurScale = this.blurScale;
  54159. serializationObject.useKernelBlur = this.useKernelBlur;
  54160. serializationObject.transparencyShadow = this._transparencyShadow;
  54161. serializationObject.renderList = [];
  54162. if (shadowMap.renderList) {
  54163. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54164. var mesh = shadowMap.renderList[meshIndex];
  54165. serializationObject.renderList.push(mesh.id);
  54166. }
  54167. }
  54168. return serializationObject;
  54169. };
  54170. /**
  54171. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54172. */
  54173. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54174. //casting to point light, as light is missing the position attr and typescript complains.
  54175. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54176. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54177. var shadowMap = shadowGenerator.getShadowMap();
  54178. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54179. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54180. meshes.forEach(function (mesh) {
  54181. if (!shadowMap) {
  54182. return;
  54183. }
  54184. if (!shadowMap.renderList) {
  54185. shadowMap.renderList = [];
  54186. }
  54187. shadowMap.renderList.push(mesh);
  54188. });
  54189. }
  54190. if (parsedShadowGenerator.usePoissonSampling) {
  54191. shadowGenerator.usePoissonSampling = true;
  54192. }
  54193. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54194. shadowGenerator.useExponentialShadowMap = true;
  54195. }
  54196. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54197. shadowGenerator.useBlurExponentialShadowMap = true;
  54198. }
  54199. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54200. shadowGenerator.useCloseExponentialShadowMap = true;
  54201. }
  54202. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54203. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54204. }
  54205. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54206. shadowGenerator.useExponentialShadowMap = true;
  54207. }
  54208. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54209. shadowGenerator.useBlurExponentialShadowMap = true;
  54210. }
  54211. if (parsedShadowGenerator.depthScale) {
  54212. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54213. }
  54214. if (parsedShadowGenerator.blurScale) {
  54215. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54216. }
  54217. if (parsedShadowGenerator.blurBoxOffset) {
  54218. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54219. }
  54220. if (parsedShadowGenerator.useKernelBlur) {
  54221. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54222. }
  54223. if (parsedShadowGenerator.blurKernel) {
  54224. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54225. }
  54226. if (parsedShadowGenerator.bias !== undefined) {
  54227. shadowGenerator.bias = parsedShadowGenerator.bias;
  54228. }
  54229. if (parsedShadowGenerator.darkness) {
  54230. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54231. }
  54232. if (parsedShadowGenerator.transparencyShadow) {
  54233. shadowGenerator.setTransparencyShadow(true);
  54234. }
  54235. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54236. return shadowGenerator;
  54237. };
  54238. ShadowGenerator._FILTER_NONE = 0;
  54239. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54240. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54241. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54242. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54243. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54244. return ShadowGenerator;
  54245. }());
  54246. BABYLON.ShadowGenerator = ShadowGenerator;
  54247. })(BABYLON || (BABYLON = {}));
  54248. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54249. var BABYLON;
  54250. (function (BABYLON) {
  54251. var DefaultLoadingScreen = /** @class */ (function () {
  54252. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54253. if (_loadingText === void 0) { _loadingText = ""; }
  54254. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54255. var _this = this;
  54256. this._renderingCanvas = _renderingCanvas;
  54257. this._loadingText = _loadingText;
  54258. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54259. // Resize
  54260. this._resizeLoadingUI = function () {
  54261. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54262. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54263. if (!_this._loadingDiv) {
  54264. return;
  54265. }
  54266. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54267. _this._loadingDiv.style.left = canvasRect.left + "px";
  54268. _this._loadingDiv.style.top = canvasRect.top + "px";
  54269. _this._loadingDiv.style.width = canvasRect.width + "px";
  54270. _this._loadingDiv.style.height = canvasRect.height + "px";
  54271. };
  54272. }
  54273. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54274. if (this._loadingDiv) {
  54275. // Do not add a loading screen if there is already one
  54276. return;
  54277. }
  54278. this._loadingDiv = document.createElement("div");
  54279. this._loadingDiv.id = "babylonjsLoadingDiv";
  54280. this._loadingDiv.style.opacity = "0";
  54281. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54282. this._loadingDiv.style.pointerEvents = "none";
  54283. // Loading text
  54284. this._loadingTextDiv = document.createElement("div");
  54285. this._loadingTextDiv.style.position = "absolute";
  54286. this._loadingTextDiv.style.left = "0";
  54287. this._loadingTextDiv.style.top = "50%";
  54288. this._loadingTextDiv.style.marginTop = "80px";
  54289. this._loadingTextDiv.style.width = "100%";
  54290. this._loadingTextDiv.style.height = "20px";
  54291. this._loadingTextDiv.style.fontFamily = "Arial";
  54292. this._loadingTextDiv.style.fontSize = "14px";
  54293. this._loadingTextDiv.style.color = "white";
  54294. this._loadingTextDiv.style.textAlign = "center";
  54295. this._loadingTextDiv.innerHTML = "Loading";
  54296. this._loadingDiv.appendChild(this._loadingTextDiv);
  54297. //set the predefined text
  54298. this._loadingTextDiv.innerHTML = this._loadingText;
  54299. // Generating keyframes
  54300. var style = document.createElement('style');
  54301. style.type = 'text/css';
  54302. 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 }";
  54303. style.innerHTML = keyFrames;
  54304. document.getElementsByTagName('head')[0].appendChild(style);
  54305. // Loading img
  54306. var imgBack = new Image();
  54307. 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";
  54308. imgBack.style.position = "absolute";
  54309. imgBack.style.left = "50%";
  54310. imgBack.style.top = "50%";
  54311. imgBack.style.marginLeft = "-60px";
  54312. imgBack.style.marginTop = "-60px";
  54313. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54314. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54315. imgBack.style.transformOrigin = "50% 50%";
  54316. imgBack.style.webkitTransformOrigin = "50% 50%";
  54317. this._loadingDiv.appendChild(imgBack);
  54318. this._resizeLoadingUI();
  54319. window.addEventListener("resize", this._resizeLoadingUI);
  54320. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54321. document.body.appendChild(this._loadingDiv);
  54322. this._loadingDiv.style.opacity = "1";
  54323. };
  54324. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54325. var _this = this;
  54326. if (!this._loadingDiv) {
  54327. return;
  54328. }
  54329. var onTransitionEnd = function () {
  54330. if (!_this._loadingDiv) {
  54331. return;
  54332. }
  54333. document.body.removeChild(_this._loadingDiv);
  54334. window.removeEventListener("resize", _this._resizeLoadingUI);
  54335. _this._loadingDiv = null;
  54336. };
  54337. this._loadingDiv.style.opacity = "0";
  54338. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54339. };
  54340. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54341. set: function (text) {
  54342. this._loadingText = text;
  54343. if (this._loadingTextDiv) {
  54344. this._loadingTextDiv.innerHTML = this._loadingText;
  54345. }
  54346. },
  54347. enumerable: true,
  54348. configurable: true
  54349. });
  54350. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54351. get: function () {
  54352. return this._loadingDivBackgroundColor;
  54353. },
  54354. set: function (color) {
  54355. this._loadingDivBackgroundColor = color;
  54356. if (!this._loadingDiv) {
  54357. return;
  54358. }
  54359. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54360. },
  54361. enumerable: true,
  54362. configurable: true
  54363. });
  54364. return DefaultLoadingScreen;
  54365. }());
  54366. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54367. })(BABYLON || (BABYLON = {}));
  54368. //# sourceMappingURL=babylon.loadingScreen.js.map
  54369. var BABYLON;
  54370. (function (BABYLON) {
  54371. var SceneLoaderProgressEvent = /** @class */ (function () {
  54372. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54373. this.lengthComputable = lengthComputable;
  54374. this.loaded = loaded;
  54375. this.total = total;
  54376. }
  54377. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54378. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54379. };
  54380. return SceneLoaderProgressEvent;
  54381. }());
  54382. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54383. var SceneLoader = /** @class */ (function () {
  54384. function SceneLoader() {
  54385. }
  54386. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54387. get: function () {
  54388. return 0;
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54394. get: function () {
  54395. return 1;
  54396. },
  54397. enumerable: true,
  54398. configurable: true
  54399. });
  54400. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54401. get: function () {
  54402. return 2;
  54403. },
  54404. enumerable: true,
  54405. configurable: true
  54406. });
  54407. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54408. get: function () {
  54409. return 3;
  54410. },
  54411. enumerable: true,
  54412. configurable: true
  54413. });
  54414. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54415. get: function () {
  54416. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54417. },
  54418. set: function (value) {
  54419. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54420. },
  54421. enumerable: true,
  54422. configurable: true
  54423. });
  54424. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54425. get: function () {
  54426. return SceneLoader._ShowLoadingScreen;
  54427. },
  54428. set: function (value) {
  54429. SceneLoader._ShowLoadingScreen = value;
  54430. },
  54431. enumerable: true,
  54432. configurable: true
  54433. });
  54434. Object.defineProperty(SceneLoader, "loggingLevel", {
  54435. get: function () {
  54436. return SceneLoader._loggingLevel;
  54437. },
  54438. set: function (value) {
  54439. SceneLoader._loggingLevel = value;
  54440. },
  54441. enumerable: true,
  54442. configurable: true
  54443. });
  54444. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54445. get: function () {
  54446. return SceneLoader._CleanBoneMatrixWeights;
  54447. },
  54448. set: function (value) {
  54449. SceneLoader._CleanBoneMatrixWeights = value;
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. SceneLoader._getDefaultPlugin = function () {
  54455. return SceneLoader._registeredPlugins[".babylon"];
  54456. };
  54457. SceneLoader._getPluginForExtension = function (extension) {
  54458. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54459. if (registeredPlugin) {
  54460. return registeredPlugin;
  54461. }
  54462. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54463. return SceneLoader._getDefaultPlugin();
  54464. };
  54465. SceneLoader._getPluginForDirectLoad = function (data) {
  54466. for (var extension in SceneLoader._registeredPlugins) {
  54467. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54468. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54469. return SceneLoader._registeredPlugins[extension];
  54470. }
  54471. }
  54472. return SceneLoader._getDefaultPlugin();
  54473. };
  54474. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54475. if (sceneFilename.name) {
  54476. sceneFilename = sceneFilename.name;
  54477. }
  54478. var queryStringPosition = sceneFilename.indexOf("?");
  54479. if (queryStringPosition !== -1) {
  54480. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54481. }
  54482. var dotPosition = sceneFilename.lastIndexOf(".");
  54483. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54484. return SceneLoader._getPluginForExtension(extension);
  54485. };
  54486. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54487. SceneLoader._getDirectLoad = function (sceneFilename) {
  54488. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54489. return sceneFilename.substr(5);
  54490. }
  54491. return null;
  54492. };
  54493. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54494. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54495. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54496. var plugin;
  54497. if (registeredPlugin.plugin.createPlugin) {
  54498. plugin = registeredPlugin.plugin.createPlugin();
  54499. }
  54500. else {
  54501. plugin = registeredPlugin.plugin;
  54502. }
  54503. var useArrayBuffer = registeredPlugin.isBinary;
  54504. var database;
  54505. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54506. var dataCallback = function (data, responseURL) {
  54507. if (scene.isDisposed) {
  54508. onError("Scene has been disposed");
  54509. return;
  54510. }
  54511. scene.database = database;
  54512. onSuccess(plugin, data, responseURL);
  54513. };
  54514. var request = null;
  54515. var pluginDisposed = false;
  54516. var onDisposeObservable = plugin.onDisposeObservable;
  54517. if (onDisposeObservable) {
  54518. onDisposeObservable.add(function () {
  54519. pluginDisposed = true;
  54520. if (request) {
  54521. request.abort();
  54522. request = null;
  54523. }
  54524. onDispose();
  54525. });
  54526. }
  54527. var manifestChecked = function () {
  54528. if (pluginDisposed) {
  54529. return;
  54530. }
  54531. var url = rootUrl + sceneFilename;
  54532. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54533. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54534. } : undefined, database, useArrayBuffer, function (request, exception) {
  54535. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54536. });
  54537. };
  54538. if (directLoad) {
  54539. dataCallback(directLoad);
  54540. return plugin;
  54541. }
  54542. if (rootUrl.indexOf("file:") === -1) {
  54543. if (scene.getEngine().enableOfflineSupport) {
  54544. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54545. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54546. }
  54547. else {
  54548. manifestChecked();
  54549. }
  54550. }
  54551. else {
  54552. var fileOrString = sceneFilename;
  54553. if (fileOrString.name) {
  54554. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54555. }
  54556. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54557. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54558. }
  54559. else {
  54560. onError("Unable to find file named " + sceneFilename);
  54561. }
  54562. }
  54563. return plugin;
  54564. };
  54565. // Public functions
  54566. SceneLoader.GetPluginForExtension = function (extension) {
  54567. return SceneLoader._getPluginForExtension(extension).plugin;
  54568. };
  54569. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54570. return !!SceneLoader._registeredPlugins[extension];
  54571. };
  54572. SceneLoader.RegisterPlugin = function (plugin) {
  54573. if (typeof plugin.extensions === "string") {
  54574. var extension = plugin.extensions;
  54575. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54576. plugin: plugin,
  54577. isBinary: false
  54578. };
  54579. }
  54580. else {
  54581. var extensions = plugin.extensions;
  54582. Object.keys(extensions).forEach(function (extension) {
  54583. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54584. plugin: plugin,
  54585. isBinary: extensions[extension].isBinary
  54586. };
  54587. });
  54588. }
  54589. };
  54590. /**
  54591. * Import meshes into a scene
  54592. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54593. * @param rootUrl a string that defines the root url for scene and resources
  54594. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54595. * @param scene the instance of BABYLON.Scene to append to
  54596. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54597. * @param onProgress a callback with a progress event for each file being loaded
  54598. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54599. */
  54600. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54601. if (onSuccess === void 0) { onSuccess = null; }
  54602. if (onProgress === void 0) { onProgress = null; }
  54603. if (onError === void 0) { onError = null; }
  54604. if (pluginExtension === void 0) { pluginExtension = null; }
  54605. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54606. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54607. return null;
  54608. }
  54609. var loadingToken = {};
  54610. scene._addPendingData(loadingToken);
  54611. var disposeHandler = function () {
  54612. scene._removePendingData(loadingToken);
  54613. };
  54614. var errorHandler = function (message, exception) {
  54615. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54616. if (onError) {
  54617. onError(scene, errorMessage, exception);
  54618. }
  54619. else {
  54620. BABYLON.Tools.Error(errorMessage);
  54621. // should the exception be thrown?
  54622. }
  54623. disposeHandler();
  54624. };
  54625. var progressHandler = onProgress ? function (event) {
  54626. try {
  54627. onProgress(event);
  54628. }
  54629. catch (e) {
  54630. errorHandler("Error in onProgress callback", e);
  54631. }
  54632. } : undefined;
  54633. var successHandler = function (meshes, particleSystems, skeletons) {
  54634. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54635. if (onSuccess) {
  54636. try {
  54637. onSuccess(meshes, particleSystems, skeletons);
  54638. }
  54639. catch (e) {
  54640. errorHandler("Error in onSuccess callback", e);
  54641. }
  54642. }
  54643. scene._removePendingData(loadingToken);
  54644. };
  54645. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54646. if (plugin.rewriteRootURL) {
  54647. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54648. }
  54649. if (plugin.importMesh) {
  54650. var syncedPlugin = plugin;
  54651. var meshes = new Array();
  54652. var particleSystems = new Array();
  54653. var skeletons = new Array();
  54654. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54655. return;
  54656. }
  54657. scene.loadingPluginName = plugin.name;
  54658. successHandler(meshes, particleSystems, skeletons);
  54659. }
  54660. else {
  54661. var asyncedPlugin = plugin;
  54662. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54663. scene.loadingPluginName = plugin.name;
  54664. successHandler(meshes, particleSystems, skeletons);
  54665. }, progressHandler, errorHandler);
  54666. }
  54667. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54668. };
  54669. /**
  54670. * Load a scene
  54671. * @param rootUrl a string that defines the root url for scene and resources
  54672. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54673. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54674. * @param onSuccess a callback with the scene when import succeeds
  54675. * @param onProgress a callback with a progress event for each file being loaded
  54676. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54677. */
  54678. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54679. if (onSuccess === void 0) { onSuccess = null; }
  54680. if (onProgress === void 0) { onProgress = null; }
  54681. if (onError === void 0) { onError = null; }
  54682. if (pluginExtension === void 0) { pluginExtension = null; }
  54683. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54684. };
  54685. /**
  54686. * Append a scene
  54687. * @param rootUrl a string that defines the root url for scene and resources
  54688. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54689. * @param scene is the instance of BABYLON.Scene to append to
  54690. * @param onSuccess a callback with the scene when import succeeds
  54691. * @param onProgress a callback with a progress event for each file being loaded
  54692. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54693. */
  54694. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54695. if (onSuccess === void 0) { onSuccess = null; }
  54696. if (onProgress === void 0) { onProgress = null; }
  54697. if (onError === void 0) { onError = null; }
  54698. if (pluginExtension === void 0) { pluginExtension = null; }
  54699. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54700. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54701. return null;
  54702. }
  54703. if (SceneLoader.ShowLoadingScreen) {
  54704. scene.getEngine().displayLoadingUI();
  54705. }
  54706. var loadingToken = {};
  54707. scene._addPendingData(loadingToken);
  54708. var disposeHandler = function () {
  54709. scene._removePendingData(loadingToken);
  54710. scene.getEngine().hideLoadingUI();
  54711. };
  54712. var errorHandler = function (message, exception) {
  54713. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54714. if (onError) {
  54715. onError(scene, errorMessage, exception);
  54716. }
  54717. else {
  54718. BABYLON.Tools.Error(errorMessage);
  54719. // should the exception be thrown?
  54720. }
  54721. disposeHandler();
  54722. };
  54723. var progressHandler = onProgress ? function (event) {
  54724. try {
  54725. onProgress(event);
  54726. }
  54727. catch (e) {
  54728. errorHandler("Error in onProgress callback", e);
  54729. }
  54730. } : undefined;
  54731. var successHandler = function () {
  54732. if (onSuccess) {
  54733. try {
  54734. onSuccess(scene);
  54735. }
  54736. catch (e) {
  54737. errorHandler("Error in onSuccess callback", e);
  54738. }
  54739. }
  54740. scene._removePendingData(loadingToken);
  54741. };
  54742. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54743. if (plugin.load) {
  54744. var syncedPlugin = plugin;
  54745. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54746. return;
  54747. }
  54748. scene.loadingPluginName = plugin.name;
  54749. successHandler();
  54750. }
  54751. else {
  54752. var asyncedPlugin = plugin;
  54753. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54754. scene.loadingPluginName = plugin.name;
  54755. successHandler();
  54756. }, progressHandler, errorHandler);
  54757. }
  54758. if (SceneLoader.ShowLoadingScreen) {
  54759. scene.executeWhenReady(function () {
  54760. scene.getEngine().hideLoadingUI();
  54761. });
  54762. }
  54763. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54764. };
  54765. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54766. if (onSuccess === void 0) { onSuccess = null; }
  54767. if (onProgress === void 0) { onProgress = null; }
  54768. if (onError === void 0) { onError = null; }
  54769. if (pluginExtension === void 0) { pluginExtension = null; }
  54770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54772. return null;
  54773. }
  54774. var loadingToken = {};
  54775. scene._addPendingData(loadingToken);
  54776. var disposeHandler = function () {
  54777. scene._removePendingData(loadingToken);
  54778. };
  54779. var errorHandler = function (message, exception) {
  54780. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54781. if (onError) {
  54782. onError(scene, errorMessage, exception);
  54783. }
  54784. else {
  54785. BABYLON.Tools.Error(errorMessage);
  54786. // should the exception be thrown?
  54787. }
  54788. disposeHandler();
  54789. };
  54790. var progressHandler = onProgress ? function (event) {
  54791. try {
  54792. onProgress(event);
  54793. }
  54794. catch (e) {
  54795. errorHandler("Error in onProgress callback", e);
  54796. }
  54797. } : undefined;
  54798. var successHandler = function (assets) {
  54799. if (onSuccess) {
  54800. try {
  54801. onSuccess(assets);
  54802. }
  54803. catch (e) {
  54804. errorHandler("Error in onSuccess callback", e);
  54805. }
  54806. }
  54807. scene._removePendingData(loadingToken);
  54808. };
  54809. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54810. if (plugin.loadAssets) {
  54811. var syncedPlugin = plugin;
  54812. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54813. if (!assetContainer) {
  54814. return;
  54815. }
  54816. scene.loadingPluginName = plugin.name;
  54817. successHandler(assetContainer);
  54818. }
  54819. else if (plugin.loadAssetsAsync) {
  54820. var asyncedPlugin = plugin;
  54821. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54822. if (assetContainer) {
  54823. scene.loadingPluginName = plugin.name;
  54824. successHandler(assetContainer);
  54825. }
  54826. }, progressHandler, errorHandler);
  54827. }
  54828. else {
  54829. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54830. }
  54831. if (SceneLoader.ShowLoadingScreen) {
  54832. scene.executeWhenReady(function () {
  54833. scene.getEngine().hideLoadingUI();
  54834. });
  54835. }
  54836. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54837. };
  54838. // Flags
  54839. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54840. SceneLoader._ShowLoadingScreen = true;
  54841. SceneLoader._CleanBoneMatrixWeights = false;
  54842. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54843. // Members
  54844. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54845. SceneLoader._registeredPlugins = {};
  54846. return SceneLoader;
  54847. }());
  54848. BABYLON.SceneLoader = SceneLoader;
  54849. ;
  54850. })(BABYLON || (BABYLON = {}));
  54851. //# sourceMappingURL=babylon.sceneLoader.js.map
  54852. var BABYLON;
  54853. (function (BABYLON) {
  54854. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54855. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54856. var parsedMaterial = parsedData.materials[index];
  54857. if (parsedMaterial.id === id) {
  54858. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54859. }
  54860. }
  54861. return null;
  54862. };
  54863. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54864. for (var i in names) {
  54865. if (mesh.name === names[i]) {
  54866. hierarchyIds.push(mesh.id);
  54867. return true;
  54868. }
  54869. }
  54870. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54871. hierarchyIds.push(mesh.id);
  54872. return true;
  54873. }
  54874. return false;
  54875. };
  54876. var logOperation = function (operation, producer) {
  54877. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54878. };
  54879. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  54880. if (addToScene === void 0) { addToScene = false; }
  54881. var container = new BABYLON.AssetContainer(scene);
  54882. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54883. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54884. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54885. // and avoid problems with multiple concurrent .babylon loads.
  54886. var log = "importScene has failed JSON parse";
  54887. try {
  54888. var parsedData = JSON.parse(data);
  54889. log = "";
  54890. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54891. var index;
  54892. var cache;
  54893. // Lights
  54894. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54895. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54896. var parsedLight = parsedData.lights[index];
  54897. var light = BABYLON.Light.Parse(parsedLight, scene);
  54898. if (light) {
  54899. container.lights.push(light);
  54900. log += (index === 0 ? "\n\tLights:" : "");
  54901. log += "\n\t\t" + light.toString(fullDetails);
  54902. }
  54903. }
  54904. }
  54905. // Animations
  54906. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54907. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54908. var parsedAnimation = parsedData.animations[index];
  54909. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54910. scene.animations.push(animation);
  54911. container.animations.push(animation);
  54912. log += (index === 0 ? "\n\tAnimations:" : "");
  54913. log += "\n\t\t" + animation.toString(fullDetails);
  54914. }
  54915. }
  54916. // Materials
  54917. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54918. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54919. var parsedMaterial = parsedData.materials[index];
  54920. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54921. container.materials.push(mat);
  54922. log += (index === 0 ? "\n\tMaterials:" : "");
  54923. log += "\n\t\t" + mat.toString(fullDetails);
  54924. }
  54925. }
  54926. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54927. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54928. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54929. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54930. container.multiMaterials.push(mmat);
  54931. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54932. log += "\n\t\t" + mmat.toString(fullDetails);
  54933. }
  54934. }
  54935. // Morph targets
  54936. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54937. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54938. var managerData = _a[_i];
  54939. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  54940. }
  54941. }
  54942. // Skeletons
  54943. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54944. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54945. var parsedSkeleton = parsedData.skeletons[index];
  54946. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54947. container.skeletons.push(skeleton);
  54948. log += (index === 0 ? "\n\tSkeletons:" : "");
  54949. log += "\n\t\t" + skeleton.toString(fullDetails);
  54950. }
  54951. }
  54952. // Geometries
  54953. var geometries = parsedData.geometries;
  54954. if (geometries !== undefined && geometries !== null) {
  54955. var addedGeometry = new Array();
  54956. // Boxes
  54957. var boxes = geometries.boxes;
  54958. if (boxes !== undefined && boxes !== null) {
  54959. for (index = 0, cache = boxes.length; index < cache; index++) {
  54960. var parsedBox = boxes[index];
  54961. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  54962. }
  54963. }
  54964. // Spheres
  54965. var spheres = geometries.spheres;
  54966. if (spheres !== undefined && spheres !== null) {
  54967. for (index = 0, cache = spheres.length; index < cache; index++) {
  54968. var parsedSphere = spheres[index];
  54969. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  54970. }
  54971. }
  54972. // Cylinders
  54973. var cylinders = geometries.cylinders;
  54974. if (cylinders !== undefined && cylinders !== null) {
  54975. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54976. var parsedCylinder = cylinders[index];
  54977. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  54978. }
  54979. }
  54980. // Toruses
  54981. var toruses = geometries.toruses;
  54982. if (toruses !== undefined && toruses !== null) {
  54983. for (index = 0, cache = toruses.length; index < cache; index++) {
  54984. var parsedTorus = toruses[index];
  54985. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  54986. }
  54987. }
  54988. // Grounds
  54989. var grounds = geometries.grounds;
  54990. if (grounds !== undefined && grounds !== null) {
  54991. for (index = 0, cache = grounds.length; index < cache; index++) {
  54992. var parsedGround = grounds[index];
  54993. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  54994. }
  54995. }
  54996. // Planes
  54997. var planes = geometries.planes;
  54998. if (planes !== undefined && planes !== null) {
  54999. for (index = 0, cache = planes.length; index < cache; index++) {
  55000. var parsedPlane = planes[index];
  55001. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  55002. }
  55003. }
  55004. // TorusKnots
  55005. var torusKnots = geometries.torusKnots;
  55006. if (torusKnots !== undefined && torusKnots !== null) {
  55007. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55008. var parsedTorusKnot = torusKnots[index];
  55009. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  55010. }
  55011. }
  55012. // VertexData
  55013. var vertexData = geometries.vertexData;
  55014. if (vertexData !== undefined && vertexData !== null) {
  55015. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55016. var parsedVertexData = vertexData[index];
  55017. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55018. }
  55019. }
  55020. addedGeometry.forEach(function (g) {
  55021. if (g) {
  55022. container.geometries.push(g);
  55023. }
  55024. });
  55025. }
  55026. // Transform nodes
  55027. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55028. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55029. var parsedTransformNode = parsedData.transformNodes[index];
  55030. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55031. container.transformNodes.push(node);
  55032. }
  55033. }
  55034. // Meshes
  55035. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55036. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55037. var parsedMesh = parsedData.meshes[index];
  55038. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55039. container.meshes.push(mesh);
  55040. log += (index === 0 ? "\n\tMeshes:" : "");
  55041. log += "\n\t\t" + mesh.toString(fullDetails);
  55042. }
  55043. }
  55044. // Cameras
  55045. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55046. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55047. var parsedCamera = parsedData.cameras[index];
  55048. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55049. container.cameras.push(camera);
  55050. log += (index === 0 ? "\n\tCameras:" : "");
  55051. log += "\n\t\t" + camera.toString(fullDetails);
  55052. }
  55053. }
  55054. // Browsing all the graph to connect the dots
  55055. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55056. var camera = scene.cameras[index];
  55057. if (camera._waitingParentId) {
  55058. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55059. camera._waitingParentId = null;
  55060. }
  55061. }
  55062. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55063. var light_1 = scene.lights[index];
  55064. if (light_1 && light_1._waitingParentId) {
  55065. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55066. light_1._waitingParentId = null;
  55067. }
  55068. }
  55069. // Sounds
  55070. // TODO: add sound
  55071. var loadedSounds = [];
  55072. var loadedSound;
  55073. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55074. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55075. var parsedSound = parsedData.sounds[index];
  55076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55077. if (!parsedSound.url)
  55078. parsedSound.url = parsedSound.name;
  55079. if (!loadedSounds[parsedSound.url]) {
  55080. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55081. loadedSounds[parsedSound.url] = loadedSound;
  55082. container.sounds.push(loadedSound);
  55083. }
  55084. else {
  55085. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55086. }
  55087. }
  55088. else {
  55089. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55090. }
  55091. }
  55092. }
  55093. loadedSounds = [];
  55094. // Connect parents & children and parse actions
  55095. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55096. var transformNode = scene.transformNodes[index];
  55097. if (transformNode._waitingParentId) {
  55098. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55099. transformNode._waitingParentId = null;
  55100. }
  55101. }
  55102. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55103. var mesh = scene.meshes[index];
  55104. if (mesh._waitingParentId) {
  55105. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55106. mesh._waitingParentId = null;
  55107. }
  55108. if (mesh._waitingActions) {
  55109. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55110. mesh._waitingActions = null;
  55111. }
  55112. }
  55113. // freeze world matrix application
  55114. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55115. var currentMesh = scene.meshes[index];
  55116. if (currentMesh._waitingFreezeWorldMatrix) {
  55117. currentMesh.freezeWorldMatrix();
  55118. currentMesh._waitingFreezeWorldMatrix = null;
  55119. }
  55120. else {
  55121. currentMesh.computeWorldMatrix(true);
  55122. }
  55123. }
  55124. // Particles Systems
  55125. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55126. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55127. var parsedParticleSystem = parsedData.particleSystems[index];
  55128. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55129. container.particleSystems.push(ps);
  55130. }
  55131. }
  55132. // Lens flares
  55133. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55134. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55135. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55136. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55137. container.lensFlareSystems.push(lf);
  55138. }
  55139. }
  55140. // Shadows
  55141. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55142. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55143. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55144. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55145. container.shadowGenerators.push(sg);
  55146. }
  55147. }
  55148. // Lights exclusions / inclusions
  55149. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55150. var light_2 = scene.lights[index];
  55151. // Excluded check
  55152. if (light_2._excludedMeshesIds.length > 0) {
  55153. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55154. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55155. if (excludedMesh) {
  55156. light_2.excludedMeshes.push(excludedMesh);
  55157. }
  55158. }
  55159. light_2._excludedMeshesIds = [];
  55160. }
  55161. // Included check
  55162. if (light_2._includedOnlyMeshesIds.length > 0) {
  55163. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55164. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55165. if (includedOnlyMesh) {
  55166. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55167. }
  55168. }
  55169. light_2._includedOnlyMeshesIds = [];
  55170. }
  55171. }
  55172. // Actions (scene)
  55173. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55174. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55175. }
  55176. if (!addToScene) {
  55177. container.removeAllFromScene();
  55178. }
  55179. return container;
  55180. }
  55181. catch (err) {
  55182. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55183. if (onError) {
  55184. onError(msg, err);
  55185. }
  55186. else {
  55187. BABYLON.Tools.Log(msg);
  55188. throw err;
  55189. }
  55190. }
  55191. finally {
  55192. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55193. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55194. }
  55195. }
  55196. return null;
  55197. };
  55198. BABYLON.SceneLoader.RegisterPlugin({
  55199. name: "babylon.js",
  55200. extensions: ".babylon",
  55201. canDirectLoad: function (data) {
  55202. if (data.indexOf("babylon") !== -1) {
  55203. return true;
  55204. }
  55205. return false;
  55206. },
  55207. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55208. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55209. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55210. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55211. // and avoid problems with multiple concurrent .babylon loads.
  55212. var log = "importMesh has failed JSON parse";
  55213. try {
  55214. var parsedData = JSON.parse(data);
  55215. log = "";
  55216. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55217. if (!meshesNames) {
  55218. meshesNames = null;
  55219. }
  55220. else if (!Array.isArray(meshesNames)) {
  55221. meshesNames = [meshesNames];
  55222. }
  55223. var hierarchyIds = new Array();
  55224. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55225. var loadedSkeletonsIds = [];
  55226. var loadedMaterialsIds = [];
  55227. var index;
  55228. var cache;
  55229. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55230. var parsedMesh = parsedData.meshes[index];
  55231. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55232. if (meshesNames !== null) {
  55233. // Remove found mesh name from list.
  55234. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55235. }
  55236. //Geometry?
  55237. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55238. //does the file contain geometries?
  55239. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55240. //find the correct geometry and add it to the scene
  55241. var found = false;
  55242. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55243. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55244. return;
  55245. }
  55246. else {
  55247. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55248. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55249. switch (geometryType) {
  55250. case "boxes":
  55251. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55252. break;
  55253. case "spheres":
  55254. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55255. break;
  55256. case "cylinders":
  55257. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55258. break;
  55259. case "toruses":
  55260. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55261. break;
  55262. case "grounds":
  55263. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55264. break;
  55265. case "planes":
  55266. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55267. break;
  55268. case "torusKnots":
  55269. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55270. break;
  55271. case "vertexData":
  55272. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55273. break;
  55274. }
  55275. found = true;
  55276. }
  55277. });
  55278. }
  55279. });
  55280. if (found === false) {
  55281. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55282. }
  55283. }
  55284. }
  55285. // Material ?
  55286. if (parsedMesh.materialId) {
  55287. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55288. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55289. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55290. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55291. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55292. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55293. var subMatId = parsedMultiMaterial.materials[matIndex];
  55294. loadedMaterialsIds.push(subMatId);
  55295. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55296. log += "\n\tMaterial " + mat.toString(fullDetails);
  55297. }
  55298. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55299. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55300. materialFound = true;
  55301. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55302. break;
  55303. }
  55304. }
  55305. }
  55306. if (materialFound === false) {
  55307. loadedMaterialsIds.push(parsedMesh.materialId);
  55308. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55309. if (!mat) {
  55310. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55311. }
  55312. else {
  55313. log += "\n\tMaterial " + mat.toString(fullDetails);
  55314. }
  55315. }
  55316. }
  55317. // Skeleton ?
  55318. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55319. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55320. if (skeletonAlreadyLoaded === false) {
  55321. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55322. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55323. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55324. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55325. skeletons.push(skeleton);
  55326. loadedSkeletonsIds.push(parsedSkeleton.id);
  55327. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55328. }
  55329. }
  55330. }
  55331. }
  55332. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55333. meshes.push(mesh);
  55334. log += "\n\tMesh " + mesh.toString(fullDetails);
  55335. }
  55336. }
  55337. // Connecting parents
  55338. var currentMesh;
  55339. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55340. currentMesh = scene.meshes[index];
  55341. if (currentMesh._waitingParentId) {
  55342. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55343. currentMesh._waitingParentId = null;
  55344. }
  55345. }
  55346. // freeze and compute world matrix application
  55347. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55348. currentMesh = scene.meshes[index];
  55349. if (currentMesh._waitingFreezeWorldMatrix) {
  55350. currentMesh.freezeWorldMatrix();
  55351. currentMesh._waitingFreezeWorldMatrix = null;
  55352. }
  55353. else {
  55354. currentMesh.computeWorldMatrix(true);
  55355. }
  55356. }
  55357. }
  55358. // Particles
  55359. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55360. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55361. var parsedParticleSystem = parsedData.particleSystems[index];
  55362. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55363. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55364. }
  55365. }
  55366. }
  55367. return true;
  55368. }
  55369. catch (err) {
  55370. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55371. if (onError) {
  55372. onError(msg, err);
  55373. }
  55374. else {
  55375. BABYLON.Tools.Log(msg);
  55376. throw err;
  55377. }
  55378. }
  55379. finally {
  55380. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55381. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55382. }
  55383. }
  55384. return false;
  55385. },
  55386. load: function (scene, data, rootUrl, onError) {
  55387. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55388. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55389. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55390. // and avoid problems with multiple concurrent .babylon loads.
  55391. var log = "importScene has failed JSON parse";
  55392. try {
  55393. var parsedData = JSON.parse(data);
  55394. log = "";
  55395. // Scene
  55396. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55397. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55398. }
  55399. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55400. scene.autoClear = parsedData.autoClear;
  55401. }
  55402. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55403. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55404. }
  55405. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55406. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55407. }
  55408. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55409. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55410. }
  55411. // Fog
  55412. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55413. scene.fogMode = parsedData.fogMode;
  55414. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55415. scene.fogStart = parsedData.fogStart;
  55416. scene.fogEnd = parsedData.fogEnd;
  55417. scene.fogDensity = parsedData.fogDensity;
  55418. log += "\tFog mode for scene: ";
  55419. switch (scene.fogMode) {
  55420. // getters not compiling, so using hardcoded
  55421. case 1:
  55422. log += "exp\n";
  55423. break;
  55424. case 2:
  55425. log += "exp2\n";
  55426. break;
  55427. case 3:
  55428. log += "linear\n";
  55429. break;
  55430. }
  55431. }
  55432. //Physics
  55433. if (parsedData.physicsEnabled) {
  55434. var physicsPlugin;
  55435. if (parsedData.physicsEngine === "cannon") {
  55436. physicsPlugin = new BABYLON.CannonJSPlugin();
  55437. }
  55438. else if (parsedData.physicsEngine === "oimo") {
  55439. physicsPlugin = new BABYLON.OimoJSPlugin();
  55440. }
  55441. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55442. //else - default engine, which is currently oimo
  55443. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55444. scene.enablePhysics(physicsGravity, physicsPlugin);
  55445. }
  55446. // Metadata
  55447. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55448. scene.metadata = parsedData.metadata;
  55449. }
  55450. //collisions, if defined. otherwise, default is true
  55451. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55452. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55453. }
  55454. scene.workerCollisions = !!parsedData.workerCollisions;
  55455. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55456. if (!container) {
  55457. return false;
  55458. }
  55459. if (parsedData.autoAnimate) {
  55460. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55461. }
  55462. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55463. scene.setActiveCameraByID(parsedData.activeCameraID);
  55464. }
  55465. // Environment texture
  55466. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55467. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55468. if (parsedData.createDefaultSkybox === true) {
  55469. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55470. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55471. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55472. }
  55473. }
  55474. // Finish
  55475. return true;
  55476. }
  55477. catch (err) {
  55478. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55479. if (onError) {
  55480. onError(msg, err);
  55481. }
  55482. else {
  55483. BABYLON.Tools.Log(msg);
  55484. throw err;
  55485. }
  55486. }
  55487. finally {
  55488. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55489. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55490. }
  55491. }
  55492. return false;
  55493. },
  55494. loadAssets: function (scene, data, rootUrl, onError) {
  55495. var container = loadAssets(scene, data, rootUrl, onerror);
  55496. return container;
  55497. }
  55498. });
  55499. })(BABYLON || (BABYLON = {}));
  55500. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55501. var BABYLON;
  55502. (function (BABYLON) {
  55503. var FilesInput = /** @class */ (function () {
  55504. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55505. this.onProcessFileCallback = function () { return true; };
  55506. this._engine = engine;
  55507. this._currentScene = scene;
  55508. this._sceneLoadedCallback = sceneLoadedCallback;
  55509. this._progressCallback = progressCallback;
  55510. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55511. this._textureLoadingCallback = textureLoadingCallback;
  55512. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55513. this._onReloadCallback = onReloadCallback;
  55514. this._errorCallback = errorCallback;
  55515. }
  55516. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55517. var _this = this;
  55518. if (elementToMonitor) {
  55519. this._elementToMonitor = elementToMonitor;
  55520. this._dragEnterHandler = function (e) { _this.drag(e); };
  55521. this._dragOverHandler = function (e) { _this.drag(e); };
  55522. this._dropHandler = function (e) { _this.drop(e); };
  55523. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55524. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55525. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55526. }
  55527. };
  55528. FilesInput.prototype.dispose = function () {
  55529. if (!this._elementToMonitor) {
  55530. return;
  55531. }
  55532. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55533. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55534. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55535. };
  55536. FilesInput.prototype.renderFunction = function () {
  55537. if (this._additionalRenderLoopLogicCallback) {
  55538. this._additionalRenderLoopLogicCallback();
  55539. }
  55540. if (this._currentScene) {
  55541. if (this._textureLoadingCallback) {
  55542. var remaining = this._currentScene.getWaitingItemsCount();
  55543. if (remaining > 0) {
  55544. this._textureLoadingCallback(remaining);
  55545. }
  55546. }
  55547. this._currentScene.render();
  55548. }
  55549. };
  55550. FilesInput.prototype.drag = function (e) {
  55551. e.stopPropagation();
  55552. e.preventDefault();
  55553. };
  55554. FilesInput.prototype.drop = function (eventDrop) {
  55555. eventDrop.stopPropagation();
  55556. eventDrop.preventDefault();
  55557. this.loadFiles(eventDrop);
  55558. };
  55559. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55560. var _this = this;
  55561. var reader = folder.createReader();
  55562. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55563. reader.readEntries(function (entries) {
  55564. remaining.count += entries.length;
  55565. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55566. var entry = entries_1[_i];
  55567. if (entry.isFile) {
  55568. entry.file(function (file) {
  55569. file.correctName = relativePath + file.name;
  55570. files.push(file);
  55571. if (--remaining.count === 0) {
  55572. callback();
  55573. }
  55574. });
  55575. }
  55576. else if (entry.isDirectory) {
  55577. _this._traverseFolder(entry, files, remaining, callback);
  55578. }
  55579. }
  55580. if (--remaining.count) {
  55581. callback();
  55582. }
  55583. });
  55584. };
  55585. FilesInput.prototype._processFiles = function (files) {
  55586. for (var i = 0; i < files.length; i++) {
  55587. var name = files[i].correctName.toLowerCase();
  55588. var extension = name.split('.').pop();
  55589. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55590. continue;
  55591. }
  55592. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55593. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55594. this._sceneFileToLoad = files[i];
  55595. }
  55596. else {
  55597. FilesInput.FilesToLoad[name] = files[i];
  55598. }
  55599. }
  55600. };
  55601. FilesInput.prototype.loadFiles = function (event) {
  55602. var _this = this;
  55603. if (this._startingProcessingFilesCallback)
  55604. this._startingProcessingFilesCallback();
  55605. // Handling data transfer via drag'n'drop
  55606. if (event && event.dataTransfer && event.dataTransfer.files) {
  55607. this._filesToLoad = event.dataTransfer.files;
  55608. }
  55609. // Handling files from input files
  55610. if (event && event.target && event.target.files) {
  55611. this._filesToLoad = event.target.files;
  55612. }
  55613. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55614. var files_1 = new Array();
  55615. var folders = [];
  55616. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55617. for (var i = 0; i < this._filesToLoad.length; i++) {
  55618. var fileToLoad = this._filesToLoad[i];
  55619. var name_1 = fileToLoad.name.toLowerCase();
  55620. var entry = void 0;
  55621. fileToLoad.correctName = name_1;
  55622. if (items) {
  55623. var item = items[i];
  55624. if (item.getAsEntry) {
  55625. entry = item.getAsEntry();
  55626. }
  55627. else if (item.webkitGetAsEntry) {
  55628. entry = item.webkitGetAsEntry();
  55629. }
  55630. }
  55631. if (!entry) {
  55632. files_1.push(fileToLoad);
  55633. }
  55634. else {
  55635. if (entry.isDirectory) {
  55636. folders.push(entry);
  55637. }
  55638. else {
  55639. files_1.push(fileToLoad);
  55640. }
  55641. }
  55642. }
  55643. if (folders.length === 0) {
  55644. this._processFiles(files_1);
  55645. this._processReload();
  55646. }
  55647. else {
  55648. var remaining = { count: folders.length };
  55649. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55650. var folder = folders_1[_i];
  55651. this._traverseFolder(folder, files_1, remaining, function () {
  55652. _this._processFiles(files_1);
  55653. if (remaining.count === 0) {
  55654. _this._processReload();
  55655. }
  55656. });
  55657. }
  55658. }
  55659. }
  55660. };
  55661. FilesInput.prototype._processReload = function () {
  55662. if (this._onReloadCallback) {
  55663. this._onReloadCallback(this._sceneFileToLoad);
  55664. }
  55665. else {
  55666. this.reload();
  55667. }
  55668. };
  55669. FilesInput.prototype.reload = function () {
  55670. var _this = this;
  55671. // If a scene file has been provided
  55672. if (this._sceneFileToLoad) {
  55673. if (this._currentScene) {
  55674. if (BABYLON.Tools.errorsCount > 0) {
  55675. BABYLON.Tools.ClearLogCache();
  55676. }
  55677. this._engine.stopRenderLoop();
  55678. this._currentScene.dispose();
  55679. }
  55680. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55681. _this._currentScene = newScene;
  55682. if (_this._sceneLoadedCallback) {
  55683. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55684. }
  55685. // Wait for textures and shaders to be ready
  55686. _this._currentScene.executeWhenReady(function () {
  55687. _this._engine.runRenderLoop(function () {
  55688. _this.renderFunction();
  55689. });
  55690. });
  55691. }, function (progress) {
  55692. if (_this._progressCallback) {
  55693. _this._progressCallback(progress);
  55694. }
  55695. }, function (scene, message) {
  55696. _this._currentScene = scene;
  55697. if (_this._errorCallback) {
  55698. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55699. }
  55700. });
  55701. }
  55702. else {
  55703. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55704. }
  55705. };
  55706. FilesInput.FilesToLoad = {};
  55707. return FilesInput;
  55708. }());
  55709. BABYLON.FilesInput = FilesInput;
  55710. })(BABYLON || (BABYLON = {}));
  55711. //# sourceMappingURL=babylon.filesInput.js.map
  55712. var BABYLON;
  55713. (function (BABYLON) {
  55714. /**
  55715. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55716. * The underlying implementation relies on an associative array to ensure the best performances.
  55717. * The value can be anything including 'null' but except 'undefined'
  55718. */
  55719. var StringDictionary = /** @class */ (function () {
  55720. function StringDictionary() {
  55721. this._count = 0;
  55722. this._data = {};
  55723. }
  55724. /**
  55725. * This will clear this dictionary and copy the content from the 'source' one.
  55726. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55727. * @param source the dictionary to take the content from and copy to this dictionary
  55728. */
  55729. StringDictionary.prototype.copyFrom = function (source) {
  55730. var _this = this;
  55731. this.clear();
  55732. source.forEach(function (t, v) { return _this.add(t, v); });
  55733. };
  55734. /**
  55735. * Get a value based from its key
  55736. * @param key the given key to get the matching value from
  55737. * @return the value if found, otherwise undefined is returned
  55738. */
  55739. StringDictionary.prototype.get = function (key) {
  55740. var val = this._data[key];
  55741. if (val !== undefined) {
  55742. return val;
  55743. }
  55744. return undefined;
  55745. };
  55746. /**
  55747. * Get a value from its key or add it if it doesn't exist.
  55748. * This method will ensure you that a given key/data will be present in the dictionary.
  55749. * @param key the given key to get the matching value from
  55750. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55751. * The factory will only be invoked if there's no data for the given key.
  55752. * @return the value corresponding to the key.
  55753. */
  55754. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55755. var val = this.get(key);
  55756. if (val !== undefined) {
  55757. return val;
  55758. }
  55759. val = factory(key);
  55760. if (val) {
  55761. this.add(key, val);
  55762. }
  55763. return val;
  55764. };
  55765. /**
  55766. * Get a value from its key if present in the dictionary otherwise add it
  55767. * @param key the key to get the value from
  55768. * @param val if there's no such key/value pair in the dictionary add it with this value
  55769. * @return the value corresponding to the key
  55770. */
  55771. StringDictionary.prototype.getOrAdd = function (key, val) {
  55772. var curVal = this.get(key);
  55773. if (curVal !== undefined) {
  55774. return curVal;
  55775. }
  55776. this.add(key, val);
  55777. return val;
  55778. };
  55779. /**
  55780. * Check if there's a given key in the dictionary
  55781. * @param key the key to check for
  55782. * @return true if the key is present, false otherwise
  55783. */
  55784. StringDictionary.prototype.contains = function (key) {
  55785. return this._data[key] !== undefined;
  55786. };
  55787. /**
  55788. * Add a new key and its corresponding value
  55789. * @param key the key to add
  55790. * @param value the value corresponding to the key
  55791. * @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
  55792. */
  55793. StringDictionary.prototype.add = function (key, value) {
  55794. if (this._data[key] !== undefined) {
  55795. return false;
  55796. }
  55797. this._data[key] = value;
  55798. ++this._count;
  55799. return true;
  55800. };
  55801. StringDictionary.prototype.set = function (key, value) {
  55802. if (this._data[key] === undefined) {
  55803. return false;
  55804. }
  55805. this._data[key] = value;
  55806. return true;
  55807. };
  55808. /**
  55809. * Get the element of the given key and remove it from the dictionary
  55810. * @param key
  55811. */
  55812. StringDictionary.prototype.getAndRemove = function (key) {
  55813. var val = this.get(key);
  55814. if (val !== undefined) {
  55815. delete this._data[key];
  55816. --this._count;
  55817. return val;
  55818. }
  55819. return null;
  55820. };
  55821. /**
  55822. * Remove a key/value from the dictionary.
  55823. * @param key the key to remove
  55824. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55825. */
  55826. StringDictionary.prototype.remove = function (key) {
  55827. if (this.contains(key)) {
  55828. delete this._data[key];
  55829. --this._count;
  55830. return true;
  55831. }
  55832. return false;
  55833. };
  55834. /**
  55835. * Clear the whole content of the dictionary
  55836. */
  55837. StringDictionary.prototype.clear = function () {
  55838. this._data = {};
  55839. this._count = 0;
  55840. };
  55841. Object.defineProperty(StringDictionary.prototype, "count", {
  55842. get: function () {
  55843. return this._count;
  55844. },
  55845. enumerable: true,
  55846. configurable: true
  55847. });
  55848. /**
  55849. * Execute a callback on each key/val of the dictionary.
  55850. * Note that you can remove any element in this dictionary in the callback implementation
  55851. * @param callback the callback to execute on a given key/value pair
  55852. */
  55853. StringDictionary.prototype.forEach = function (callback) {
  55854. for (var cur in this._data) {
  55855. var val = this._data[cur];
  55856. callback(cur, val);
  55857. }
  55858. };
  55859. /**
  55860. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55861. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55862. * Note that you can remove any element in this dictionary in the callback implementation
  55863. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55864. */
  55865. StringDictionary.prototype.first = function (callback) {
  55866. for (var cur in this._data) {
  55867. var val = this._data[cur];
  55868. var res = callback(cur, val);
  55869. if (res) {
  55870. return res;
  55871. }
  55872. }
  55873. return null;
  55874. };
  55875. return StringDictionary;
  55876. }());
  55877. BABYLON.StringDictionary = StringDictionary;
  55878. })(BABYLON || (BABYLON = {}));
  55879. //# sourceMappingURL=babylon.stringDictionary.js.map
  55880. var BABYLON;
  55881. (function (BABYLON) {
  55882. var Tags = /** @class */ (function () {
  55883. function Tags() {
  55884. }
  55885. Tags.EnableFor = function (obj) {
  55886. obj._tags = obj._tags || {};
  55887. obj.hasTags = function () {
  55888. return Tags.HasTags(obj);
  55889. };
  55890. obj.addTags = function (tagsString) {
  55891. return Tags.AddTagsTo(obj, tagsString);
  55892. };
  55893. obj.removeTags = function (tagsString) {
  55894. return Tags.RemoveTagsFrom(obj, tagsString);
  55895. };
  55896. obj.matchesTagsQuery = function (tagsQuery) {
  55897. return Tags.MatchesQuery(obj, tagsQuery);
  55898. };
  55899. };
  55900. Tags.DisableFor = function (obj) {
  55901. delete obj._tags;
  55902. delete obj.hasTags;
  55903. delete obj.addTags;
  55904. delete obj.removeTags;
  55905. delete obj.matchesTagsQuery;
  55906. };
  55907. Tags.HasTags = function (obj) {
  55908. if (!obj._tags) {
  55909. return false;
  55910. }
  55911. return !BABYLON.Tools.IsEmpty(obj._tags);
  55912. };
  55913. Tags.GetTags = function (obj, asString) {
  55914. if (asString === void 0) { asString = true; }
  55915. if (!obj._tags) {
  55916. return null;
  55917. }
  55918. if (asString) {
  55919. var tagsArray = [];
  55920. for (var tag in obj._tags) {
  55921. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55922. tagsArray.push(tag);
  55923. }
  55924. }
  55925. return tagsArray.join(" ");
  55926. }
  55927. else {
  55928. return obj._tags;
  55929. }
  55930. };
  55931. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55932. // a tag cannot start with '||', '&&', and '!'
  55933. // it cannot contain whitespaces
  55934. Tags.AddTagsTo = function (obj, tagsString) {
  55935. if (!tagsString) {
  55936. return;
  55937. }
  55938. if (typeof tagsString !== "string") {
  55939. return;
  55940. }
  55941. var tags = tagsString.split(" ");
  55942. tags.forEach(function (tag, index, array) {
  55943. Tags._AddTagTo(obj, tag);
  55944. });
  55945. };
  55946. Tags._AddTagTo = function (obj, tag) {
  55947. tag = tag.trim();
  55948. if (tag === "" || tag === "true" || tag === "false") {
  55949. return;
  55950. }
  55951. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55952. return;
  55953. }
  55954. Tags.EnableFor(obj);
  55955. obj._tags[tag] = true;
  55956. };
  55957. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55958. if (!Tags.HasTags(obj)) {
  55959. return;
  55960. }
  55961. var tags = tagsString.split(" ");
  55962. for (var t in tags) {
  55963. Tags._RemoveTagFrom(obj, tags[t]);
  55964. }
  55965. };
  55966. Tags._RemoveTagFrom = function (obj, tag) {
  55967. delete obj._tags[tag];
  55968. };
  55969. Tags.MatchesQuery = function (obj, tagsQuery) {
  55970. if (tagsQuery === undefined) {
  55971. return true;
  55972. }
  55973. if (tagsQuery === "") {
  55974. return Tags.HasTags(obj);
  55975. }
  55976. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55977. };
  55978. return Tags;
  55979. }());
  55980. BABYLON.Tags = Tags;
  55981. })(BABYLON || (BABYLON = {}));
  55982. //# sourceMappingURL=babylon.tags.js.map
  55983. var BABYLON;
  55984. (function (BABYLON) {
  55985. var AndOrNotEvaluator = /** @class */ (function () {
  55986. function AndOrNotEvaluator() {
  55987. }
  55988. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55989. if (!query.match(/\([^\(\)]*\)/g)) {
  55990. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55991. }
  55992. else {
  55993. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55994. // remove parenthesis
  55995. r = r.slice(1, r.length - 1);
  55996. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55997. });
  55998. }
  55999. if (query === "true") {
  56000. return true;
  56001. }
  56002. if (query === "false") {
  56003. return false;
  56004. }
  56005. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  56006. };
  56007. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  56008. evaluateCallback = evaluateCallback || (function (r) {
  56009. return r === "true" ? true : false;
  56010. });
  56011. var result;
  56012. var or = parenthesisContent.split("||");
  56013. for (var i in or) {
  56014. if (or.hasOwnProperty(i)) {
  56015. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56016. var and = ori.split("&&");
  56017. if (and.length > 1) {
  56018. for (var j = 0; j < and.length; ++j) {
  56019. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56020. if (andj !== "true" && andj !== "false") {
  56021. if (andj[0] === "!") {
  56022. result = !evaluateCallback(andj.substring(1));
  56023. }
  56024. else {
  56025. result = evaluateCallback(andj);
  56026. }
  56027. }
  56028. else {
  56029. result = andj === "true" ? true : false;
  56030. }
  56031. if (!result) {
  56032. ori = "false";
  56033. break;
  56034. }
  56035. }
  56036. }
  56037. if (result || ori === "true") {
  56038. result = true;
  56039. break;
  56040. }
  56041. // result equals false (or undefined)
  56042. if (ori !== "true" && ori !== "false") {
  56043. if (ori[0] === "!") {
  56044. result = !evaluateCallback(ori.substring(1));
  56045. }
  56046. else {
  56047. result = evaluateCallback(ori);
  56048. }
  56049. }
  56050. else {
  56051. result = ori === "true" ? true : false;
  56052. }
  56053. }
  56054. }
  56055. // the whole parenthesis scope is replaced by 'true' or 'false'
  56056. return result ? "true" : "false";
  56057. };
  56058. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56059. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56060. // remove whitespaces
  56061. r = r.replace(/[\s]/g, function () { return ""; });
  56062. return r.length % 2 ? "!" : "";
  56063. });
  56064. booleanString = booleanString.trim();
  56065. if (booleanString === "!true") {
  56066. booleanString = "false";
  56067. }
  56068. else if (booleanString === "!false") {
  56069. booleanString = "true";
  56070. }
  56071. return booleanString;
  56072. };
  56073. return AndOrNotEvaluator;
  56074. }());
  56075. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56076. })(BABYLON || (BABYLON = {}));
  56077. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56078. var BABYLON;
  56079. (function (BABYLON) {
  56080. var Database = /** @class */ (function () {
  56081. function Database(urlToScene, callbackManifestChecked) {
  56082. // Handling various flavors of prefixed version of IndexedDB
  56083. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56084. this.callbackManifestChecked = callbackManifestChecked;
  56085. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56086. this.db = null;
  56087. this._enableSceneOffline = false;
  56088. this._enableTexturesOffline = false;
  56089. this.manifestVersionFound = 0;
  56090. this.mustUpdateRessources = false;
  56091. this.hasReachedQuota = false;
  56092. if (!Database.IDBStorageEnabled) {
  56093. this.callbackManifestChecked(true);
  56094. }
  56095. else {
  56096. this.checkManifestFile();
  56097. }
  56098. }
  56099. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56100. get: function () {
  56101. return this._enableSceneOffline;
  56102. },
  56103. enumerable: true,
  56104. configurable: true
  56105. });
  56106. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56107. get: function () {
  56108. return this._enableTexturesOffline;
  56109. },
  56110. enumerable: true,
  56111. configurable: true
  56112. });
  56113. Database.prototype.checkManifestFile = function () {
  56114. var _this = this;
  56115. var noManifestFile = function () {
  56116. _this._enableSceneOffline = false;
  56117. _this._enableTexturesOffline = false;
  56118. _this.callbackManifestChecked(false);
  56119. };
  56120. var timeStampUsed = false;
  56121. var manifestURL = this.currentSceneUrl + ".manifest";
  56122. var xhr = new XMLHttpRequest();
  56123. if (navigator.onLine) {
  56124. // Adding a timestamp to by-pass browsers' cache
  56125. timeStampUsed = true;
  56126. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56127. }
  56128. xhr.open("GET", manifestURL, true);
  56129. xhr.addEventListener("load", function () {
  56130. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56131. try {
  56132. var manifestFile = JSON.parse(xhr.response);
  56133. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56134. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56135. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56136. _this.manifestVersionFound = manifestFile.version;
  56137. }
  56138. if (_this.callbackManifestChecked) {
  56139. _this.callbackManifestChecked(true);
  56140. }
  56141. }
  56142. catch (ex) {
  56143. noManifestFile();
  56144. }
  56145. }
  56146. else {
  56147. noManifestFile();
  56148. }
  56149. }, false);
  56150. xhr.addEventListener("error", function (event) {
  56151. if (timeStampUsed) {
  56152. timeStampUsed = false;
  56153. // Let's retry without the timeStamp
  56154. // It could fail when coupled with HTML5 Offline API
  56155. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56156. xhr.open("GET", retryManifestURL, true);
  56157. xhr.send();
  56158. }
  56159. else {
  56160. noManifestFile();
  56161. }
  56162. }, false);
  56163. try {
  56164. xhr.send();
  56165. }
  56166. catch (ex) {
  56167. BABYLON.Tools.Error("Error on XHR send request.");
  56168. this.callbackManifestChecked(false);
  56169. }
  56170. };
  56171. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56172. var _this = this;
  56173. var handleError = function () {
  56174. _this.isSupported = false;
  56175. if (errorCallback)
  56176. errorCallback();
  56177. };
  56178. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56179. // Your browser doesn't support IndexedDB
  56180. this.isSupported = false;
  56181. if (errorCallback)
  56182. errorCallback();
  56183. }
  56184. else {
  56185. // If the DB hasn't been opened or created yet
  56186. if (!this.db) {
  56187. this.hasReachedQuota = false;
  56188. this.isSupported = true;
  56189. var request = this.idbFactory.open("babylonjs", 1);
  56190. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56191. request.onerror = function (event) {
  56192. handleError();
  56193. };
  56194. // executes when a version change transaction cannot complete due to other active transactions
  56195. request.onblocked = function (event) {
  56196. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56197. handleError();
  56198. };
  56199. // DB has been opened successfully
  56200. request.onsuccess = function (event) {
  56201. _this.db = request.result;
  56202. successCallback();
  56203. };
  56204. // Initialization of the DB. Creating Scenes & Textures stores
  56205. request.onupgradeneeded = function (event) {
  56206. _this.db = (event.target).result;
  56207. if (_this.db) {
  56208. try {
  56209. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56210. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56211. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56212. }
  56213. catch (ex) {
  56214. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56215. handleError();
  56216. }
  56217. }
  56218. };
  56219. }
  56220. else {
  56221. if (successCallback)
  56222. successCallback();
  56223. }
  56224. }
  56225. };
  56226. Database.prototype.loadImageFromDB = function (url, image) {
  56227. var _this = this;
  56228. var completeURL = Database.ReturnFullUrlLocation(url);
  56229. var saveAndLoadImage = function () {
  56230. if (!_this.hasReachedQuota && _this.db !== null) {
  56231. // the texture is not yet in the DB, let's try to save it
  56232. _this._saveImageIntoDBAsync(completeURL, image);
  56233. }
  56234. else {
  56235. image.src = url;
  56236. }
  56237. };
  56238. if (!this.mustUpdateRessources) {
  56239. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56240. }
  56241. else {
  56242. saveAndLoadImage();
  56243. }
  56244. };
  56245. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56246. if (this.isSupported && this.db !== null) {
  56247. var texture;
  56248. var transaction = this.db.transaction(["textures"]);
  56249. transaction.onabort = function (event) {
  56250. image.src = url;
  56251. };
  56252. transaction.oncomplete = function (event) {
  56253. var blobTextureURL;
  56254. if (texture) {
  56255. var URL = window.URL || window.webkitURL;
  56256. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56257. image.onerror = function () {
  56258. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56259. image.src = url;
  56260. };
  56261. image.src = blobTextureURL;
  56262. }
  56263. else {
  56264. notInDBCallback();
  56265. }
  56266. };
  56267. var getRequest = transaction.objectStore("textures").get(url);
  56268. getRequest.onsuccess = function (event) {
  56269. texture = (event.target).result;
  56270. };
  56271. getRequest.onerror = function (event) {
  56272. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56273. image.src = url;
  56274. };
  56275. }
  56276. else {
  56277. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56278. image.src = url;
  56279. }
  56280. };
  56281. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56282. var _this = this;
  56283. if (this.isSupported) {
  56284. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56285. var generateBlobUrl = function () {
  56286. var blobTextureURL;
  56287. if (blob) {
  56288. var URL = window.URL || window.webkitURL;
  56289. try {
  56290. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56291. }
  56292. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56293. catch (ex) {
  56294. blobTextureURL = URL.createObjectURL(blob);
  56295. }
  56296. }
  56297. if (blobTextureURL) {
  56298. image.src = blobTextureURL;
  56299. }
  56300. };
  56301. if (Database.IsUASupportingBlobStorage) {
  56302. var xhr = new XMLHttpRequest(), blob;
  56303. xhr.open("GET", url, true);
  56304. xhr.responseType = "blob";
  56305. xhr.addEventListener("load", function () {
  56306. if (xhr.status === 200 && _this.db) {
  56307. // Blob as response (XHR2)
  56308. blob = xhr.response;
  56309. var transaction = _this.db.transaction(["textures"], "readwrite");
  56310. // the transaction could abort because of a QuotaExceededError error
  56311. transaction.onabort = function (event) {
  56312. try {
  56313. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56314. var srcElement = (event.srcElement || event.target);
  56315. var error = srcElement.error;
  56316. if (error && error.name === "QuotaExceededError") {
  56317. _this.hasReachedQuota = true;
  56318. }
  56319. }
  56320. catch (ex) { }
  56321. generateBlobUrl();
  56322. };
  56323. transaction.oncomplete = function (event) {
  56324. generateBlobUrl();
  56325. };
  56326. var newTexture = { textureUrl: url, data: blob };
  56327. try {
  56328. // Put the blob into the dabase
  56329. var addRequest = transaction.objectStore("textures").put(newTexture);
  56330. addRequest.onsuccess = function (event) {
  56331. };
  56332. addRequest.onerror = function (event) {
  56333. generateBlobUrl();
  56334. };
  56335. }
  56336. catch (ex) {
  56337. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56338. if (ex.code === 25) {
  56339. Database.IsUASupportingBlobStorage = false;
  56340. }
  56341. image.src = url;
  56342. }
  56343. }
  56344. else {
  56345. image.src = url;
  56346. }
  56347. }, false);
  56348. xhr.addEventListener("error", function (event) {
  56349. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56350. image.src = url;
  56351. }, false);
  56352. xhr.send();
  56353. }
  56354. else {
  56355. image.src = url;
  56356. }
  56357. }
  56358. else {
  56359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56360. image.src = url;
  56361. }
  56362. };
  56363. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56364. var _this = this;
  56365. var updateVersion = function () {
  56366. // the version is not yet in the DB or we need to update it
  56367. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56368. };
  56369. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56370. };
  56371. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56372. var _this = this;
  56373. if (this.isSupported && this.db) {
  56374. var version;
  56375. try {
  56376. var transaction = this.db.transaction(["versions"]);
  56377. transaction.oncomplete = function (event) {
  56378. if (version) {
  56379. // If the version in the JSON file is > than the version in DB
  56380. if (_this.manifestVersionFound > version.data) {
  56381. _this.mustUpdateRessources = true;
  56382. updateInDBCallback();
  56383. }
  56384. else {
  56385. callback(version.data);
  56386. }
  56387. }
  56388. else {
  56389. _this.mustUpdateRessources = true;
  56390. updateInDBCallback();
  56391. }
  56392. };
  56393. transaction.onabort = function (event) {
  56394. callback(-1);
  56395. };
  56396. var getRequest = transaction.objectStore("versions").get(url);
  56397. getRequest.onsuccess = function (event) {
  56398. version = (event.target).result;
  56399. };
  56400. getRequest.onerror = function (event) {
  56401. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56402. callback(-1);
  56403. };
  56404. }
  56405. catch (ex) {
  56406. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56407. callback(-1);
  56408. }
  56409. }
  56410. else {
  56411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56412. callback(-1);
  56413. }
  56414. };
  56415. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56416. var _this = this;
  56417. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56418. try {
  56419. // Open a transaction to the database
  56420. var transaction = this.db.transaction(["versions"], "readwrite");
  56421. // the transaction could abort because of a QuotaExceededError error
  56422. transaction.onabort = function (event) {
  56423. try {
  56424. var error = event.srcElement['error'];
  56425. if (error && error.name === "QuotaExceededError") {
  56426. _this.hasReachedQuota = true;
  56427. }
  56428. }
  56429. catch (ex) { }
  56430. callback(-1);
  56431. };
  56432. transaction.oncomplete = function (event) {
  56433. callback(_this.manifestVersionFound);
  56434. };
  56435. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56436. // Put the scene into the database
  56437. var addRequest = transaction.objectStore("versions").put(newVersion);
  56438. addRequest.onsuccess = function (event) {
  56439. };
  56440. addRequest.onerror = function (event) {
  56441. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56442. };
  56443. }
  56444. catch (ex) {
  56445. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56446. callback(-1);
  56447. }
  56448. }
  56449. else {
  56450. callback(-1);
  56451. }
  56452. };
  56453. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56454. var _this = this;
  56455. var completeUrl = Database.ReturnFullUrlLocation(url);
  56456. var saveAndLoadFile = function () {
  56457. // the scene is not yet in the DB, let's try to save it
  56458. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56459. };
  56460. this._checkVersionFromDB(completeUrl, function (version) {
  56461. if (version !== -1) {
  56462. if (!_this.mustUpdateRessources) {
  56463. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56464. }
  56465. else {
  56466. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56467. }
  56468. }
  56469. else {
  56470. if (errorCallback) {
  56471. errorCallback();
  56472. }
  56473. }
  56474. });
  56475. };
  56476. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56477. if (this.isSupported && this.db) {
  56478. var targetStore;
  56479. if (url.indexOf(".babylon") !== -1) {
  56480. targetStore = "scenes";
  56481. }
  56482. else {
  56483. targetStore = "textures";
  56484. }
  56485. var file;
  56486. var transaction = this.db.transaction([targetStore]);
  56487. transaction.oncomplete = function (event) {
  56488. if (file) {
  56489. callback(file.data);
  56490. }
  56491. else {
  56492. notInDBCallback();
  56493. }
  56494. };
  56495. transaction.onabort = function (event) {
  56496. notInDBCallback();
  56497. };
  56498. var getRequest = transaction.objectStore(targetStore).get(url);
  56499. getRequest.onsuccess = function (event) {
  56500. file = (event.target).result;
  56501. };
  56502. getRequest.onerror = function (event) {
  56503. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56504. notInDBCallback();
  56505. };
  56506. }
  56507. else {
  56508. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56509. callback();
  56510. }
  56511. };
  56512. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56513. var _this = this;
  56514. if (this.isSupported) {
  56515. var targetStore;
  56516. if (url.indexOf(".babylon") !== -1) {
  56517. targetStore = "scenes";
  56518. }
  56519. else {
  56520. targetStore = "textures";
  56521. }
  56522. // Create XHR
  56523. var xhr = new XMLHttpRequest();
  56524. var fileData;
  56525. xhr.open("GET", url, true);
  56526. if (useArrayBuffer) {
  56527. xhr.responseType = "arraybuffer";
  56528. }
  56529. if (progressCallback) {
  56530. xhr.onprogress = progressCallback;
  56531. }
  56532. xhr.addEventListener("load", function () {
  56533. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56534. // Blob as response (XHR2)
  56535. //fileData = xhr.responseText;
  56536. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56537. if (!_this.hasReachedQuota && _this.db) {
  56538. // Open a transaction to the database
  56539. var transaction = _this.db.transaction([targetStore], "readwrite");
  56540. // the transaction could abort because of a QuotaExceededError error
  56541. transaction.onabort = function (event) {
  56542. try {
  56543. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56544. var error = event.srcElement['error'];
  56545. if (error && error.name === "QuotaExceededError") {
  56546. _this.hasReachedQuota = true;
  56547. }
  56548. }
  56549. catch (ex) { }
  56550. callback(fileData);
  56551. };
  56552. transaction.oncomplete = function (event) {
  56553. callback(fileData);
  56554. };
  56555. var newFile;
  56556. if (targetStore === "scenes") {
  56557. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56558. }
  56559. else {
  56560. newFile = { textureUrl: url, data: fileData };
  56561. }
  56562. try {
  56563. // Put the scene into the database
  56564. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56565. addRequest.onsuccess = function (event) {
  56566. };
  56567. addRequest.onerror = function (event) {
  56568. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56569. };
  56570. }
  56571. catch (ex) {
  56572. callback(fileData);
  56573. }
  56574. }
  56575. else {
  56576. callback(fileData);
  56577. }
  56578. }
  56579. else {
  56580. callback();
  56581. }
  56582. }, false);
  56583. xhr.addEventListener("error", function (event) {
  56584. BABYLON.Tools.Error("error on XHR request.");
  56585. callback();
  56586. }, false);
  56587. xhr.send();
  56588. }
  56589. else {
  56590. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56591. callback();
  56592. }
  56593. };
  56594. Database.IsUASupportingBlobStorage = true;
  56595. Database.IDBStorageEnabled = true;
  56596. Database.parseURL = function (url) {
  56597. var a = document.createElement('a');
  56598. a.href = url;
  56599. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56600. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56601. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56602. return absLocation;
  56603. };
  56604. Database.ReturnFullUrlLocation = function (url) {
  56605. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56606. return (Database.parseURL(window.location.href) + url);
  56607. }
  56608. else {
  56609. return url;
  56610. }
  56611. };
  56612. return Database;
  56613. }());
  56614. BABYLON.Database = Database;
  56615. })(BABYLON || (BABYLON = {}));
  56616. //# sourceMappingURL=babylon.database.js.map
  56617. var BABYLON;
  56618. (function (BABYLON) {
  56619. var FresnelParameters = /** @class */ (function () {
  56620. function FresnelParameters() {
  56621. this._isEnabled = true;
  56622. this.leftColor = BABYLON.Color3.White();
  56623. this.rightColor = BABYLON.Color3.Black();
  56624. this.bias = 0;
  56625. this.power = 1;
  56626. }
  56627. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56628. get: function () {
  56629. return this._isEnabled;
  56630. },
  56631. set: function (value) {
  56632. if (this._isEnabled === value) {
  56633. return;
  56634. }
  56635. this._isEnabled = value;
  56636. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56637. },
  56638. enumerable: true,
  56639. configurable: true
  56640. });
  56641. FresnelParameters.prototype.clone = function () {
  56642. var newFresnelParameters = new FresnelParameters();
  56643. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56644. return newFresnelParameters;
  56645. };
  56646. FresnelParameters.prototype.serialize = function () {
  56647. var serializationObject = {};
  56648. serializationObject.isEnabled = this.isEnabled;
  56649. serializationObject.leftColor = this.leftColor;
  56650. serializationObject.rightColor = this.rightColor;
  56651. serializationObject.bias = this.bias;
  56652. serializationObject.power = this.power;
  56653. return serializationObject;
  56654. };
  56655. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56656. var fresnelParameters = new FresnelParameters();
  56657. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56658. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56659. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56660. fresnelParameters.bias = parsedFresnelParameters.bias;
  56661. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56662. return fresnelParameters;
  56663. };
  56664. return FresnelParameters;
  56665. }());
  56666. BABYLON.FresnelParameters = FresnelParameters;
  56667. })(BABYLON || (BABYLON = {}));
  56668. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56669. var BABYLON;
  56670. (function (BABYLON) {
  56671. var MultiMaterial = /** @class */ (function (_super) {
  56672. __extends(MultiMaterial, _super);
  56673. function MultiMaterial(name, scene) {
  56674. var _this = _super.call(this, name, scene, true) || this;
  56675. scene.multiMaterials.push(_this);
  56676. _this.subMaterials = new Array();
  56677. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56678. return _this;
  56679. }
  56680. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56681. get: function () {
  56682. return this._subMaterials;
  56683. },
  56684. set: function (value) {
  56685. this._subMaterials = value;
  56686. this._hookArray(value);
  56687. },
  56688. enumerable: true,
  56689. configurable: true
  56690. });
  56691. MultiMaterial.prototype._hookArray = function (array) {
  56692. var _this = this;
  56693. var oldPush = array.push;
  56694. array.push = function () {
  56695. var items = [];
  56696. for (var _i = 0; _i < arguments.length; _i++) {
  56697. items[_i] = arguments[_i];
  56698. }
  56699. var result = oldPush.apply(array, items);
  56700. _this._markAllSubMeshesAsTexturesDirty();
  56701. return result;
  56702. };
  56703. var oldSplice = array.splice;
  56704. array.splice = function (index, deleteCount) {
  56705. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56706. _this._markAllSubMeshesAsTexturesDirty();
  56707. return deleted;
  56708. };
  56709. };
  56710. // Properties
  56711. MultiMaterial.prototype.getSubMaterial = function (index) {
  56712. if (index < 0 || index >= this.subMaterials.length) {
  56713. return this.getScene().defaultMaterial;
  56714. }
  56715. return this.subMaterials[index];
  56716. };
  56717. MultiMaterial.prototype.getActiveTextures = function () {
  56718. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56719. if (subMaterial) {
  56720. return subMaterial.getActiveTextures();
  56721. }
  56722. else {
  56723. return [];
  56724. }
  56725. }));
  56726. var _a;
  56727. };
  56728. // Methods
  56729. MultiMaterial.prototype.getClassName = function () {
  56730. return "MultiMaterial";
  56731. };
  56732. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56733. for (var index = 0; index < this.subMaterials.length; index++) {
  56734. var subMaterial = this.subMaterials[index];
  56735. if (subMaterial) {
  56736. if (subMaterial.storeEffectOnSubMeshes) {
  56737. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56738. return false;
  56739. }
  56740. continue;
  56741. }
  56742. if (!subMaterial.isReady(mesh)) {
  56743. return false;
  56744. }
  56745. }
  56746. }
  56747. return true;
  56748. };
  56749. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56750. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56751. for (var index = 0; index < this.subMaterials.length; index++) {
  56752. var subMaterial = null;
  56753. var current = this.subMaterials[index];
  56754. if (cloneChildren && current) {
  56755. subMaterial = current.clone(name + "-" + current.name);
  56756. }
  56757. else {
  56758. subMaterial = this.subMaterials[index];
  56759. }
  56760. newMultiMaterial.subMaterials.push(subMaterial);
  56761. }
  56762. return newMultiMaterial;
  56763. };
  56764. MultiMaterial.prototype.serialize = function () {
  56765. var serializationObject = {};
  56766. serializationObject.name = this.name;
  56767. serializationObject.id = this.id;
  56768. if (BABYLON.Tags) {
  56769. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56770. }
  56771. serializationObject.materials = [];
  56772. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56773. var subMat = this.subMaterials[matIndex];
  56774. if (subMat) {
  56775. serializationObject.materials.push(subMat.id);
  56776. }
  56777. else {
  56778. serializationObject.materials.push(null);
  56779. }
  56780. }
  56781. return serializationObject;
  56782. };
  56783. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56784. var scene = this.getScene();
  56785. if (!scene) {
  56786. return;
  56787. }
  56788. var index = scene.multiMaterials.indexOf(this);
  56789. if (index >= 0) {
  56790. scene.multiMaterials.splice(index, 1);
  56791. }
  56792. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56793. };
  56794. return MultiMaterial;
  56795. }(BABYLON.Material));
  56796. BABYLON.MultiMaterial = MultiMaterial;
  56797. })(BABYLON || (BABYLON = {}));
  56798. //# sourceMappingURL=babylon.multiMaterial.js.map
  56799. var BABYLON;
  56800. (function (BABYLON) {
  56801. var FreeCameraTouchInput = /** @class */ (function () {
  56802. function FreeCameraTouchInput() {
  56803. this._offsetX = null;
  56804. this._offsetY = null;
  56805. this._pointerPressed = new Array();
  56806. this.touchAngularSensibility = 200000.0;
  56807. this.touchMoveSensibility = 250.0;
  56808. }
  56809. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56810. var _this = this;
  56811. var previousPosition = null;
  56812. if (this._pointerInput === undefined) {
  56813. this._onLostFocus = function (evt) {
  56814. _this._offsetX = null;
  56815. _this._offsetY = null;
  56816. };
  56817. this._pointerInput = function (p, s) {
  56818. var evt = p.event;
  56819. if (evt.pointerType === "mouse") {
  56820. return;
  56821. }
  56822. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56823. if (!noPreventDefault) {
  56824. evt.preventDefault();
  56825. }
  56826. _this._pointerPressed.push(evt.pointerId);
  56827. if (_this._pointerPressed.length !== 1) {
  56828. return;
  56829. }
  56830. previousPosition = {
  56831. x: evt.clientX,
  56832. y: evt.clientY
  56833. };
  56834. }
  56835. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56836. if (!noPreventDefault) {
  56837. evt.preventDefault();
  56838. }
  56839. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56840. if (index === -1) {
  56841. return;
  56842. }
  56843. _this._pointerPressed.splice(index, 1);
  56844. if (index != 0) {
  56845. return;
  56846. }
  56847. previousPosition = null;
  56848. _this._offsetX = null;
  56849. _this._offsetY = null;
  56850. }
  56851. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56852. if (!noPreventDefault) {
  56853. evt.preventDefault();
  56854. }
  56855. if (!previousPosition) {
  56856. return;
  56857. }
  56858. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56859. if (index != 0) {
  56860. return;
  56861. }
  56862. _this._offsetX = evt.clientX - previousPosition.x;
  56863. _this._offsetY = -(evt.clientY - previousPosition.y);
  56864. }
  56865. };
  56866. }
  56867. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56868. if (this._onLostFocus) {
  56869. element.addEventListener("blur", this._onLostFocus);
  56870. }
  56871. };
  56872. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56873. if (this._pointerInput && element) {
  56874. if (this._observer) {
  56875. this.camera.getScene().onPointerObservable.remove(this._observer);
  56876. this._observer = null;
  56877. }
  56878. if (this._onLostFocus) {
  56879. element.removeEventListener("blur", this._onLostFocus);
  56880. this._onLostFocus = null;
  56881. }
  56882. this._pointerPressed = [];
  56883. this._offsetX = null;
  56884. this._offsetY = null;
  56885. }
  56886. };
  56887. FreeCameraTouchInput.prototype.checkInputs = function () {
  56888. if (this._offsetX && this._offsetY) {
  56889. var camera = this.camera;
  56890. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56891. if (this._pointerPressed.length > 1) {
  56892. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56893. }
  56894. else {
  56895. var speed = camera._computeLocalCameraSpeed();
  56896. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56897. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56898. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56899. }
  56900. }
  56901. };
  56902. FreeCameraTouchInput.prototype.getClassName = function () {
  56903. return "FreeCameraTouchInput";
  56904. };
  56905. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56906. return "touch";
  56907. };
  56908. __decorate([
  56909. BABYLON.serialize()
  56910. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56911. __decorate([
  56912. BABYLON.serialize()
  56913. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56914. return FreeCameraTouchInput;
  56915. }());
  56916. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56917. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56918. })(BABYLON || (BABYLON = {}));
  56919. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56920. var BABYLON;
  56921. (function (BABYLON) {
  56922. // We're mainly based on the logic defined into the FreeCamera code
  56923. var TouchCamera = /** @class */ (function (_super) {
  56924. __extends(TouchCamera, _super);
  56925. //-- end properties for backward compatibility for inputs
  56926. function TouchCamera(name, position, scene) {
  56927. var _this = _super.call(this, name, position, scene) || this;
  56928. _this.inputs.addTouch();
  56929. _this._setupInputs();
  56930. return _this;
  56931. }
  56932. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56933. //-- Begin properties for backward compatibility for inputs
  56934. get: function () {
  56935. var touch = this.inputs.attached["touch"];
  56936. if (touch)
  56937. return touch.touchAngularSensibility;
  56938. return 0;
  56939. },
  56940. set: function (value) {
  56941. var touch = this.inputs.attached["touch"];
  56942. if (touch)
  56943. touch.touchAngularSensibility = value;
  56944. },
  56945. enumerable: true,
  56946. configurable: true
  56947. });
  56948. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56949. get: function () {
  56950. var touch = this.inputs.attached["touch"];
  56951. if (touch)
  56952. return touch.touchMoveSensibility;
  56953. return 0;
  56954. },
  56955. set: function (value) {
  56956. var touch = this.inputs.attached["touch"];
  56957. if (touch)
  56958. touch.touchMoveSensibility = value;
  56959. },
  56960. enumerable: true,
  56961. configurable: true
  56962. });
  56963. TouchCamera.prototype.getClassName = function () {
  56964. return "TouchCamera";
  56965. };
  56966. TouchCamera.prototype._setupInputs = function () {
  56967. var mouse = this.inputs.attached["mouse"];
  56968. if (mouse) {
  56969. mouse.touchEnabled = false;
  56970. }
  56971. };
  56972. return TouchCamera;
  56973. }(BABYLON.FreeCamera));
  56974. BABYLON.TouchCamera = TouchCamera;
  56975. })(BABYLON || (BABYLON = {}));
  56976. //# sourceMappingURL=babylon.touchCamera.js.map
  56977. var BABYLON;
  56978. (function (BABYLON) {
  56979. var ProceduralTexture = /** @class */ (function (_super) {
  56980. __extends(ProceduralTexture, _super);
  56981. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56982. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56984. if (isCube === void 0) { isCube = false; }
  56985. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56986. _this.isCube = isCube;
  56987. _this.isEnabled = true;
  56988. _this._currentRefreshId = -1;
  56989. _this._refreshRate = 1;
  56990. _this._vertexBuffers = {};
  56991. _this._uniforms = new Array();
  56992. _this._samplers = new Array();
  56993. _this._textures = {};
  56994. _this._floats = {};
  56995. _this._floatsArrays = {};
  56996. _this._colors3 = {};
  56997. _this._colors4 = {};
  56998. _this._vectors2 = {};
  56999. _this._vectors3 = {};
  57000. _this._matrices = {};
  57001. _this._fallbackTextureUsed = false;
  57002. scene._proceduralTextures.push(_this);
  57003. _this._engine = scene.getEngine();
  57004. _this.name = name;
  57005. _this.isRenderTarget = true;
  57006. _this._size = size;
  57007. _this._generateMipMaps = generateMipMaps;
  57008. _this.setFragment(fragment);
  57009. _this._fallbackTexture = fallbackTexture;
  57010. if (isCube) {
  57011. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  57012. _this.setFloat("face", 0);
  57013. }
  57014. else {
  57015. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57016. }
  57017. // VBO
  57018. var vertices = [];
  57019. vertices.push(1, 1);
  57020. vertices.push(-1, 1);
  57021. vertices.push(-1, -1);
  57022. vertices.push(1, -1);
  57023. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57024. _this._createIndexBuffer();
  57025. return _this;
  57026. }
  57027. ProceduralTexture.prototype._createIndexBuffer = function () {
  57028. var engine = this._engine;
  57029. // Indices
  57030. var indices = [];
  57031. indices.push(0);
  57032. indices.push(1);
  57033. indices.push(2);
  57034. indices.push(0);
  57035. indices.push(2);
  57036. indices.push(3);
  57037. this._indexBuffer = engine.createIndexBuffer(indices);
  57038. };
  57039. ProceduralTexture.prototype._rebuild = function () {
  57040. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57041. if (vb) {
  57042. vb._rebuild();
  57043. }
  57044. this._createIndexBuffer();
  57045. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57046. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57047. }
  57048. };
  57049. ProceduralTexture.prototype.reset = function () {
  57050. if (this._effect === undefined) {
  57051. return;
  57052. }
  57053. var engine = this._engine;
  57054. engine._releaseEffect(this._effect);
  57055. };
  57056. ProceduralTexture.prototype.isReady = function () {
  57057. var _this = this;
  57058. var engine = this._engine;
  57059. var shaders;
  57060. if (!this._fragment) {
  57061. return false;
  57062. }
  57063. if (this._fallbackTextureUsed) {
  57064. return true;
  57065. }
  57066. if (this._fragment.fragmentElement !== undefined) {
  57067. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57068. }
  57069. else {
  57070. shaders = { vertex: "procedural", fragment: this._fragment };
  57071. }
  57072. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57073. _this.releaseInternalTexture();
  57074. if (_this._fallbackTexture) {
  57075. _this._texture = _this._fallbackTexture._texture;
  57076. if (_this._texture) {
  57077. _this._texture.incrementReferences();
  57078. }
  57079. }
  57080. _this._fallbackTextureUsed = true;
  57081. });
  57082. return this._effect.isReady();
  57083. };
  57084. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57085. this._currentRefreshId = -1;
  57086. };
  57087. ProceduralTexture.prototype.setFragment = function (fragment) {
  57088. this._fragment = fragment;
  57089. };
  57090. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57091. get: function () {
  57092. return this._refreshRate;
  57093. },
  57094. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57095. set: function (value) {
  57096. this._refreshRate = value;
  57097. this.resetRefreshCounter();
  57098. },
  57099. enumerable: true,
  57100. configurable: true
  57101. });
  57102. ProceduralTexture.prototype._shouldRender = function () {
  57103. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57104. return false;
  57105. }
  57106. if (this._fallbackTextureUsed) {
  57107. return false;
  57108. }
  57109. if (this._currentRefreshId === -1) {
  57110. this._currentRefreshId = 1;
  57111. return true;
  57112. }
  57113. if (this.refreshRate === this._currentRefreshId) {
  57114. this._currentRefreshId = 1;
  57115. return true;
  57116. }
  57117. this._currentRefreshId++;
  57118. return false;
  57119. };
  57120. ProceduralTexture.prototype.getRenderSize = function () {
  57121. return this._size;
  57122. };
  57123. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57124. if (this._fallbackTextureUsed) {
  57125. return;
  57126. }
  57127. this.releaseInternalTexture();
  57128. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57129. };
  57130. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57131. if (this._uniforms.indexOf(uniformName) === -1) {
  57132. this._uniforms.push(uniformName);
  57133. }
  57134. };
  57135. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57136. if (this._samplers.indexOf(name) === -1) {
  57137. this._samplers.push(name);
  57138. }
  57139. this._textures[name] = texture;
  57140. return this;
  57141. };
  57142. ProceduralTexture.prototype.setFloat = function (name, value) {
  57143. this._checkUniform(name);
  57144. this._floats[name] = value;
  57145. return this;
  57146. };
  57147. ProceduralTexture.prototype.setFloats = function (name, value) {
  57148. this._checkUniform(name);
  57149. this._floatsArrays[name] = value;
  57150. return this;
  57151. };
  57152. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57153. this._checkUniform(name);
  57154. this._colors3[name] = value;
  57155. return this;
  57156. };
  57157. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57158. this._checkUniform(name);
  57159. this._colors4[name] = value;
  57160. return this;
  57161. };
  57162. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57163. this._checkUniform(name);
  57164. this._vectors2[name] = value;
  57165. return this;
  57166. };
  57167. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57168. this._checkUniform(name);
  57169. this._vectors3[name] = value;
  57170. return this;
  57171. };
  57172. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57173. this._checkUniform(name);
  57174. this._matrices[name] = value;
  57175. return this;
  57176. };
  57177. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57178. var scene = this.getScene();
  57179. if (!scene) {
  57180. return;
  57181. }
  57182. var engine = this._engine;
  57183. // Render
  57184. engine.enableEffect(this._effect);
  57185. engine.setState(false);
  57186. // Texture
  57187. for (var name in this._textures) {
  57188. this._effect.setTexture(name, this._textures[name]);
  57189. }
  57190. // Float
  57191. for (name in this._floats) {
  57192. this._effect.setFloat(name, this._floats[name]);
  57193. }
  57194. // Floats
  57195. for (name in this._floatsArrays) {
  57196. this._effect.setArray(name, this._floatsArrays[name]);
  57197. }
  57198. // Color3
  57199. for (name in this._colors3) {
  57200. this._effect.setColor3(name, this._colors3[name]);
  57201. }
  57202. // Color4
  57203. for (name in this._colors4) {
  57204. var color = this._colors4[name];
  57205. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57206. }
  57207. // Vector2
  57208. for (name in this._vectors2) {
  57209. this._effect.setVector2(name, this._vectors2[name]);
  57210. }
  57211. // Vector3
  57212. for (name in this._vectors3) {
  57213. this._effect.setVector3(name, this._vectors3[name]);
  57214. }
  57215. // Matrix
  57216. for (name in this._matrices) {
  57217. this._effect.setMatrix(name, this._matrices[name]);
  57218. }
  57219. if (!this._texture) {
  57220. return;
  57221. }
  57222. if (this.isCube) {
  57223. for (var face = 0; face < 6; face++) {
  57224. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57225. // VBOs
  57226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57227. this._effect.setFloat("face", face);
  57228. // Clear
  57229. engine.clear(scene.clearColor, true, true, true);
  57230. // Draw order
  57231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57232. // Mipmaps
  57233. if (face === 5) {
  57234. engine.generateMipMapsForCubemap(this._texture);
  57235. }
  57236. }
  57237. }
  57238. else {
  57239. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57240. // VBOs
  57241. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57242. // Clear
  57243. engine.clear(scene.clearColor, true, true, true);
  57244. // Draw order
  57245. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57246. }
  57247. // Unbind
  57248. engine.unBindFramebuffer(this._texture, this.isCube);
  57249. if (this.onGenerated) {
  57250. this.onGenerated();
  57251. }
  57252. };
  57253. ProceduralTexture.prototype.clone = function () {
  57254. var textureSize = this.getSize();
  57255. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57256. // Base texture
  57257. newTexture.hasAlpha = this.hasAlpha;
  57258. newTexture.level = this.level;
  57259. // RenderTarget Texture
  57260. newTexture.coordinatesMode = this.coordinatesMode;
  57261. return newTexture;
  57262. };
  57263. ProceduralTexture.prototype.dispose = function () {
  57264. var scene = this.getScene();
  57265. if (!scene) {
  57266. return;
  57267. }
  57268. var index = scene._proceduralTextures.indexOf(this);
  57269. if (index >= 0) {
  57270. scene._proceduralTextures.splice(index, 1);
  57271. }
  57272. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57273. if (vertexBuffer) {
  57274. vertexBuffer.dispose();
  57275. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57276. }
  57277. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57278. this._indexBuffer = null;
  57279. }
  57280. _super.prototype.dispose.call(this);
  57281. };
  57282. return ProceduralTexture;
  57283. }(BABYLON.Texture));
  57284. BABYLON.ProceduralTexture = ProceduralTexture;
  57285. })(BABYLON || (BABYLON = {}));
  57286. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57287. var BABYLON;
  57288. (function (BABYLON) {
  57289. var CustomProceduralTexture = /** @class */ (function (_super) {
  57290. __extends(CustomProceduralTexture, _super);
  57291. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57292. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57293. _this._animate = true;
  57294. _this._time = 0;
  57295. _this._texturePath = texturePath;
  57296. //Try to load json
  57297. _this.loadJson(texturePath);
  57298. _this.refreshRate = 1;
  57299. return _this;
  57300. }
  57301. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57302. var _this = this;
  57303. var noConfigFile = function () {
  57304. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57305. try {
  57306. _this.setFragment(_this._texturePath);
  57307. }
  57308. catch (ex) {
  57309. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57310. }
  57311. };
  57312. var configFileUrl = jsonUrl + "/config.json";
  57313. var xhr = new XMLHttpRequest();
  57314. xhr.open("GET", configFileUrl, true);
  57315. xhr.addEventListener("load", function () {
  57316. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57317. try {
  57318. _this._config = JSON.parse(xhr.response);
  57319. _this.updateShaderUniforms();
  57320. _this.updateTextures();
  57321. _this.setFragment(_this._texturePath + "/custom");
  57322. _this._animate = _this._config.animate;
  57323. _this.refreshRate = _this._config.refreshrate;
  57324. }
  57325. catch (ex) {
  57326. noConfigFile();
  57327. }
  57328. }
  57329. else {
  57330. noConfigFile();
  57331. }
  57332. }, false);
  57333. xhr.addEventListener("error", function () {
  57334. noConfigFile();
  57335. }, false);
  57336. try {
  57337. xhr.send();
  57338. }
  57339. catch (ex) {
  57340. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57341. }
  57342. };
  57343. CustomProceduralTexture.prototype.isReady = function () {
  57344. if (!_super.prototype.isReady.call(this)) {
  57345. return false;
  57346. }
  57347. for (var name in this._textures) {
  57348. var texture = this._textures[name];
  57349. if (!texture.isReady()) {
  57350. return false;
  57351. }
  57352. }
  57353. return true;
  57354. };
  57355. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57356. var scene = this.getScene();
  57357. if (this._animate && scene) {
  57358. this._time += scene.getAnimationRatio() * 0.03;
  57359. this.updateShaderUniforms();
  57360. }
  57361. _super.prototype.render.call(this, useCameraPostProcess);
  57362. };
  57363. CustomProceduralTexture.prototype.updateTextures = function () {
  57364. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57365. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57366. }
  57367. };
  57368. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57369. if (this._config) {
  57370. for (var j = 0; j < this._config.uniforms.length; j++) {
  57371. var uniform = this._config.uniforms[j];
  57372. switch (uniform.type) {
  57373. case "float":
  57374. this.setFloat(uniform.name, uniform.value);
  57375. break;
  57376. case "color3":
  57377. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57378. break;
  57379. case "color4":
  57380. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57381. break;
  57382. case "vector2":
  57383. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57384. break;
  57385. case "vector3":
  57386. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57387. break;
  57388. }
  57389. }
  57390. }
  57391. this.setFloat("time", this._time);
  57392. };
  57393. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57394. get: function () {
  57395. return this._animate;
  57396. },
  57397. set: function (value) {
  57398. this._animate = value;
  57399. },
  57400. enumerable: true,
  57401. configurable: true
  57402. });
  57403. return CustomProceduralTexture;
  57404. }(BABYLON.ProceduralTexture));
  57405. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57406. })(BABYLON || (BABYLON = {}));
  57407. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57408. var BABYLON;
  57409. (function (BABYLON) {
  57410. var FreeCameraGamepadInput = /** @class */ (function () {
  57411. function FreeCameraGamepadInput() {
  57412. this.gamepadAngularSensibility = 200;
  57413. this.gamepadMoveSensibility = 40;
  57414. // private members
  57415. this._cameraTransform = BABYLON.Matrix.Identity();
  57416. this._deltaTransform = BABYLON.Vector3.Zero();
  57417. this._vector3 = BABYLON.Vector3.Zero();
  57418. this._vector2 = BABYLON.Vector2.Zero();
  57419. }
  57420. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57421. var _this = this;
  57422. var manager = this.camera.getScene().gamepadManager;
  57423. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57424. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57425. // prioritize XBOX gamepads.
  57426. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57427. _this.gamepad = gamepad;
  57428. }
  57429. }
  57430. });
  57431. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57432. if (_this.gamepad === gamepad) {
  57433. _this.gamepad = null;
  57434. }
  57435. });
  57436. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57437. };
  57438. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57439. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57440. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57441. this.gamepad = null;
  57442. };
  57443. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57444. if (this.gamepad && this.gamepad.leftStick) {
  57445. var camera = this.camera;
  57446. var LSValues = this.gamepad.leftStick;
  57447. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57448. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57449. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57450. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57451. var RSValues = this.gamepad.rightStick;
  57452. if (RSValues) {
  57453. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57454. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57455. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57456. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57457. }
  57458. else {
  57459. RSValues = { x: 0, y: 0 };
  57460. }
  57461. if (!camera.rotationQuaternion) {
  57462. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57463. }
  57464. else {
  57465. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57466. }
  57467. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57468. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57469. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57470. camera.cameraDirection.addInPlace(this._deltaTransform);
  57471. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57472. camera.cameraRotation.addInPlace(this._vector2);
  57473. }
  57474. };
  57475. FreeCameraGamepadInput.prototype.getClassName = function () {
  57476. return "FreeCameraGamepadInput";
  57477. };
  57478. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57479. return "gamepad";
  57480. };
  57481. __decorate([
  57482. BABYLON.serialize()
  57483. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57484. __decorate([
  57485. BABYLON.serialize()
  57486. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57487. return FreeCameraGamepadInput;
  57488. }());
  57489. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57490. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57491. })(BABYLON || (BABYLON = {}));
  57492. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57493. var BABYLON;
  57494. (function (BABYLON) {
  57495. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57496. function ArcRotateCameraGamepadInput() {
  57497. this.gamepadRotationSensibility = 80;
  57498. this.gamepadMoveSensibility = 40;
  57499. }
  57500. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57501. var _this = this;
  57502. var manager = this.camera.getScene().gamepadManager;
  57503. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57504. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57505. // prioritize XBOX gamepads.
  57506. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57507. _this.gamepad = gamepad;
  57508. }
  57509. }
  57510. });
  57511. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57512. if (_this.gamepad === gamepad) {
  57513. _this.gamepad = null;
  57514. }
  57515. });
  57516. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57517. };
  57518. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57519. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57520. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57521. this.gamepad = null;
  57522. };
  57523. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57524. if (this.gamepad) {
  57525. var camera = this.camera;
  57526. var RSValues = this.gamepad.rightStick;
  57527. if (RSValues) {
  57528. if (RSValues.x != 0) {
  57529. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57530. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57531. camera.inertialAlphaOffset += normalizedRX;
  57532. }
  57533. }
  57534. if (RSValues.y != 0) {
  57535. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57536. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57537. camera.inertialBetaOffset += normalizedRY;
  57538. }
  57539. }
  57540. }
  57541. var LSValues = this.gamepad.leftStick;
  57542. if (LSValues && LSValues.y != 0) {
  57543. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57544. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57545. this.camera.inertialRadiusOffset -= normalizedLY;
  57546. }
  57547. }
  57548. }
  57549. };
  57550. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57551. return "ArcRotateCameraGamepadInput";
  57552. };
  57553. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57554. return "gamepad";
  57555. };
  57556. __decorate([
  57557. BABYLON.serialize()
  57558. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57559. __decorate([
  57560. BABYLON.serialize()
  57561. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57562. return ArcRotateCameraGamepadInput;
  57563. }());
  57564. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57565. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57566. })(BABYLON || (BABYLON = {}));
  57567. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57568. var BABYLON;
  57569. (function (BABYLON) {
  57570. var GamepadManager = /** @class */ (function () {
  57571. function GamepadManager(_scene) {
  57572. var _this = this;
  57573. this._scene = _scene;
  57574. this._babylonGamepads = [];
  57575. this._oneGamepadConnected = false;
  57576. this._isMonitoring = false;
  57577. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57578. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57579. this._gamepadEventSupported = false;
  57580. }
  57581. else {
  57582. this._gamepadEventSupported = 'GamepadEvent' in window;
  57583. this._gamepadSupport = (navigator.getGamepads ||
  57584. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57585. }
  57586. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57587. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57588. for (var i in _this._babylonGamepads) {
  57589. var gamepad = _this._babylonGamepads[i];
  57590. if (gamepad && gamepad._isConnected) {
  57591. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57592. }
  57593. }
  57594. });
  57595. this._onGamepadConnectedEvent = function (evt) {
  57596. var gamepad = evt.gamepad;
  57597. if (gamepad.index in _this._babylonGamepads) {
  57598. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57599. return;
  57600. }
  57601. }
  57602. var newGamepad;
  57603. if (_this._babylonGamepads[gamepad.index]) {
  57604. newGamepad = _this._babylonGamepads[gamepad.index];
  57605. newGamepad.browserGamepad = gamepad;
  57606. newGamepad._isConnected = true;
  57607. }
  57608. else {
  57609. newGamepad = _this._addNewGamepad(gamepad);
  57610. }
  57611. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57612. _this._startMonitoringGamepads();
  57613. };
  57614. this._onGamepadDisconnectedEvent = function (evt) {
  57615. var gamepad = evt.gamepad;
  57616. // Remove the gamepad from the list of gamepads to monitor.
  57617. for (var i in _this._babylonGamepads) {
  57618. if (_this._babylonGamepads[i].index === gamepad.index) {
  57619. var disconnectedGamepad = _this._babylonGamepads[i];
  57620. disconnectedGamepad._isConnected = false;
  57621. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57622. break;
  57623. }
  57624. }
  57625. };
  57626. if (this._gamepadSupport) {
  57627. //first add already-connected gamepads
  57628. this._updateGamepadObjects();
  57629. if (this._babylonGamepads.length) {
  57630. this._startMonitoringGamepads();
  57631. }
  57632. // Checking if the gamepad connected event is supported (like in Firefox)
  57633. if (this._gamepadEventSupported) {
  57634. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57635. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57636. }
  57637. else {
  57638. this._startMonitoringGamepads();
  57639. }
  57640. }
  57641. }
  57642. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57643. get: function () {
  57644. return this._babylonGamepads;
  57645. },
  57646. enumerable: true,
  57647. configurable: true
  57648. });
  57649. GamepadManager.prototype.getGamepadByType = function (type) {
  57650. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57651. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57652. var gamepad = _a[_i];
  57653. if (gamepad && gamepad.type === type) {
  57654. return gamepad;
  57655. }
  57656. }
  57657. return null;
  57658. };
  57659. GamepadManager.prototype.dispose = function () {
  57660. if (this._gamepadEventSupported) {
  57661. if (this._onGamepadConnectedEvent) {
  57662. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57663. }
  57664. if (this._onGamepadDisconnectedEvent) {
  57665. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57666. }
  57667. this._onGamepadConnectedEvent = null;
  57668. this._onGamepadDisconnectedEvent = null;
  57669. }
  57670. this._babylonGamepads.forEach(function (gamepad) {
  57671. gamepad.dispose();
  57672. });
  57673. this.onGamepadConnectedObservable.clear();
  57674. this.onGamepadDisconnectedObservable.clear();
  57675. this._oneGamepadConnected = false;
  57676. this._stopMonitoringGamepads();
  57677. this._babylonGamepads = [];
  57678. };
  57679. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57680. if (!this._oneGamepadConnected) {
  57681. this._oneGamepadConnected = true;
  57682. }
  57683. var newGamepad;
  57684. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57685. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57686. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57687. }
  57688. else if (gamepad.pose) {
  57689. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57690. }
  57691. else {
  57692. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57693. }
  57694. this._babylonGamepads[newGamepad.index] = newGamepad;
  57695. return newGamepad;
  57696. };
  57697. GamepadManager.prototype._startMonitoringGamepads = function () {
  57698. if (!this._isMonitoring) {
  57699. this._isMonitoring = true;
  57700. //back-comp
  57701. if (!this._scene) {
  57702. this._checkGamepadsStatus();
  57703. }
  57704. }
  57705. };
  57706. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57707. this._isMonitoring = false;
  57708. };
  57709. GamepadManager.prototype._checkGamepadsStatus = function () {
  57710. var _this = this;
  57711. // Hack to be compatible Chrome
  57712. this._updateGamepadObjects();
  57713. for (var i in this._babylonGamepads) {
  57714. var gamepad = this._babylonGamepads[i];
  57715. if (!gamepad || !gamepad.isConnected) {
  57716. continue;
  57717. }
  57718. gamepad.update();
  57719. }
  57720. if (this._isMonitoring && !this._scene) {
  57721. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57722. }
  57723. };
  57724. // This function is called only on Chrome, which does not properly support
  57725. // connection/disconnection events and forces you to recopy again the gamepad object
  57726. GamepadManager.prototype._updateGamepadObjects = function () {
  57727. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57728. for (var i = 0; i < gamepads.length; i++) {
  57729. if (gamepads[i]) {
  57730. if (!this._babylonGamepads[gamepads[i].index]) {
  57731. var newGamepad = this._addNewGamepad(gamepads[i]);
  57732. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57733. }
  57734. else {
  57735. // Forced to copy again this object for Chrome for unknown reason
  57736. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57737. if (!this._babylonGamepads[i].isConnected) {
  57738. this._babylonGamepads[i]._isConnected = true;
  57739. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57740. }
  57741. }
  57742. }
  57743. }
  57744. };
  57745. return GamepadManager;
  57746. }());
  57747. BABYLON.GamepadManager = GamepadManager;
  57748. })(BABYLON || (BABYLON = {}));
  57749. //# sourceMappingURL=babylon.gamepadManager.js.map
  57750. var BABYLON;
  57751. (function (BABYLON) {
  57752. var StickValues = /** @class */ (function () {
  57753. function StickValues(x, y) {
  57754. this.x = x;
  57755. this.y = y;
  57756. }
  57757. return StickValues;
  57758. }());
  57759. BABYLON.StickValues = StickValues;
  57760. var Gamepad = /** @class */ (function () {
  57761. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57762. if (leftStickX === void 0) { leftStickX = 0; }
  57763. if (leftStickY === void 0) { leftStickY = 1; }
  57764. if (rightStickX === void 0) { rightStickX = 2; }
  57765. if (rightStickY === void 0) { rightStickY = 3; }
  57766. this.id = id;
  57767. this.index = index;
  57768. this.browserGamepad = browserGamepad;
  57769. this._isConnected = true;
  57770. this._invertLeftStickY = false;
  57771. this.type = Gamepad.GAMEPAD;
  57772. this._leftStickAxisX = leftStickX;
  57773. this._leftStickAxisY = leftStickY;
  57774. this._rightStickAxisX = rightStickX;
  57775. this._rightStickAxisY = rightStickY;
  57776. if (this.browserGamepad.axes.length >= 2) {
  57777. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57778. }
  57779. if (this.browserGamepad.axes.length >= 4) {
  57780. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57781. }
  57782. }
  57783. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57784. get: function () {
  57785. return this._isConnected;
  57786. },
  57787. enumerable: true,
  57788. configurable: true
  57789. });
  57790. Gamepad.prototype.onleftstickchanged = function (callback) {
  57791. this._onleftstickchanged = callback;
  57792. };
  57793. Gamepad.prototype.onrightstickchanged = function (callback) {
  57794. this._onrightstickchanged = callback;
  57795. };
  57796. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57797. get: function () {
  57798. return this._leftStick;
  57799. },
  57800. set: function (newValues) {
  57801. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57802. this._onleftstickchanged(newValues);
  57803. }
  57804. this._leftStick = newValues;
  57805. },
  57806. enumerable: true,
  57807. configurable: true
  57808. });
  57809. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57810. get: function () {
  57811. return this._rightStick;
  57812. },
  57813. set: function (newValues) {
  57814. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57815. this._onrightstickchanged(newValues);
  57816. }
  57817. this._rightStick = newValues;
  57818. },
  57819. enumerable: true,
  57820. configurable: true
  57821. });
  57822. Gamepad.prototype.update = function () {
  57823. if (this._leftStick) {
  57824. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57825. if (this._invertLeftStickY) {
  57826. this.leftStick.y *= -1;
  57827. }
  57828. }
  57829. if (this._rightStick) {
  57830. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57831. }
  57832. };
  57833. Gamepad.prototype.dispose = function () {
  57834. };
  57835. Gamepad.GAMEPAD = 0;
  57836. Gamepad.GENERIC = 1;
  57837. Gamepad.XBOX = 2;
  57838. Gamepad.POSE_ENABLED = 3;
  57839. return Gamepad;
  57840. }());
  57841. BABYLON.Gamepad = Gamepad;
  57842. var GenericPad = /** @class */ (function (_super) {
  57843. __extends(GenericPad, _super);
  57844. function GenericPad(id, index, browserGamepad) {
  57845. var _this = _super.call(this, id, index, browserGamepad) || this;
  57846. _this.onButtonDownObservable = new BABYLON.Observable();
  57847. _this.onButtonUpObservable = new BABYLON.Observable();
  57848. _this.type = Gamepad.GENERIC;
  57849. _this._buttons = new Array(browserGamepad.buttons.length);
  57850. return _this;
  57851. }
  57852. GenericPad.prototype.onbuttondown = function (callback) {
  57853. this._onbuttondown = callback;
  57854. };
  57855. GenericPad.prototype.onbuttonup = function (callback) {
  57856. this._onbuttonup = callback;
  57857. };
  57858. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57859. if (newValue !== currentValue) {
  57860. if (newValue === 1) {
  57861. if (this._onbuttondown) {
  57862. this._onbuttondown(buttonIndex);
  57863. }
  57864. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57865. }
  57866. if (newValue === 0) {
  57867. if (this._onbuttonup) {
  57868. this._onbuttonup(buttonIndex);
  57869. }
  57870. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57871. }
  57872. }
  57873. return newValue;
  57874. };
  57875. GenericPad.prototype.update = function () {
  57876. _super.prototype.update.call(this);
  57877. for (var index = 0; index < this._buttons.length; index++) {
  57878. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57879. }
  57880. };
  57881. GenericPad.prototype.dispose = function () {
  57882. _super.prototype.dispose.call(this);
  57883. this.onButtonDownObservable.clear();
  57884. this.onButtonUpObservable.clear();
  57885. };
  57886. return GenericPad;
  57887. }(Gamepad));
  57888. BABYLON.GenericPad = GenericPad;
  57889. })(BABYLON || (BABYLON = {}));
  57890. //# sourceMappingURL=babylon.gamepad.js.map
  57891. var BABYLON;
  57892. (function (BABYLON) {
  57893. var Xbox360Button;
  57894. (function (Xbox360Button) {
  57895. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57896. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57897. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57898. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57899. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57900. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57901. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57902. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57903. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57904. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57905. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57906. var Xbox360Dpad;
  57907. (function (Xbox360Dpad) {
  57908. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57909. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57910. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57911. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57912. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57913. var Xbox360Pad = /** @class */ (function (_super) {
  57914. __extends(Xbox360Pad, _super);
  57915. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57916. if (xboxOne === void 0) { xboxOne = false; }
  57917. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57918. _this._leftTrigger = 0;
  57919. _this._rightTrigger = 0;
  57920. _this.onButtonDownObservable = new BABYLON.Observable();
  57921. _this.onButtonUpObservable = new BABYLON.Observable();
  57922. _this.onPadDownObservable = new BABYLON.Observable();
  57923. _this.onPadUpObservable = new BABYLON.Observable();
  57924. _this._buttonA = 0;
  57925. _this._buttonB = 0;
  57926. _this._buttonX = 0;
  57927. _this._buttonY = 0;
  57928. _this._buttonBack = 0;
  57929. _this._buttonStart = 0;
  57930. _this._buttonLB = 0;
  57931. _this._buttonRB = 0;
  57932. _this._buttonLeftStick = 0;
  57933. _this._buttonRightStick = 0;
  57934. _this._dPadUp = 0;
  57935. _this._dPadDown = 0;
  57936. _this._dPadLeft = 0;
  57937. _this._dPadRight = 0;
  57938. _this._isXboxOnePad = false;
  57939. _this.type = BABYLON.Gamepad.XBOX;
  57940. _this._isXboxOnePad = xboxOne;
  57941. return _this;
  57942. }
  57943. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57944. this._onlefttriggerchanged = callback;
  57945. };
  57946. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57947. this._onrighttriggerchanged = callback;
  57948. };
  57949. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57950. get: function () {
  57951. return this._leftTrigger;
  57952. },
  57953. set: function (newValue) {
  57954. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57955. this._onlefttriggerchanged(newValue);
  57956. }
  57957. this._leftTrigger = newValue;
  57958. },
  57959. enumerable: true,
  57960. configurable: true
  57961. });
  57962. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57963. get: function () {
  57964. return this._rightTrigger;
  57965. },
  57966. set: function (newValue) {
  57967. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57968. this._onrighttriggerchanged(newValue);
  57969. }
  57970. this._rightTrigger = newValue;
  57971. },
  57972. enumerable: true,
  57973. configurable: true
  57974. });
  57975. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57976. this._onbuttondown = callback;
  57977. };
  57978. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57979. this._onbuttonup = callback;
  57980. };
  57981. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57982. this._ondpaddown = callback;
  57983. };
  57984. Xbox360Pad.prototype.ondpadup = function (callback) {
  57985. this._ondpadup = callback;
  57986. };
  57987. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57988. if (newValue !== currentValue) {
  57989. if (newValue === 1) {
  57990. if (this._onbuttondown) {
  57991. this._onbuttondown(buttonType);
  57992. }
  57993. this.onButtonDownObservable.notifyObservers(buttonType);
  57994. }
  57995. if (newValue === 0) {
  57996. if (this._onbuttonup) {
  57997. this._onbuttonup(buttonType);
  57998. }
  57999. this.onButtonUpObservable.notifyObservers(buttonType);
  58000. }
  58001. }
  58002. return newValue;
  58003. };
  58004. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  58005. if (newValue !== currentValue) {
  58006. if (newValue === 1) {
  58007. if (this._ondpaddown) {
  58008. this._ondpaddown(buttonType);
  58009. }
  58010. this.onPadDownObservable.notifyObservers(buttonType);
  58011. }
  58012. if (newValue === 0) {
  58013. if (this._ondpadup) {
  58014. this._ondpadup(buttonType);
  58015. }
  58016. this.onPadUpObservable.notifyObservers(buttonType);
  58017. }
  58018. }
  58019. return newValue;
  58020. };
  58021. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58022. get: function () {
  58023. return this._buttonA;
  58024. },
  58025. set: function (value) {
  58026. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58027. },
  58028. enumerable: true,
  58029. configurable: true
  58030. });
  58031. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58032. get: function () {
  58033. return this._buttonB;
  58034. },
  58035. set: function (value) {
  58036. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58037. },
  58038. enumerable: true,
  58039. configurable: true
  58040. });
  58041. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58042. get: function () {
  58043. return this._buttonX;
  58044. },
  58045. set: function (value) {
  58046. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58047. },
  58048. enumerable: true,
  58049. configurable: true
  58050. });
  58051. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58052. get: function () {
  58053. return this._buttonY;
  58054. },
  58055. set: function (value) {
  58056. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58057. },
  58058. enumerable: true,
  58059. configurable: true
  58060. });
  58061. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58062. get: function () {
  58063. return this._buttonStart;
  58064. },
  58065. set: function (value) {
  58066. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58067. },
  58068. enumerable: true,
  58069. configurable: true
  58070. });
  58071. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58072. get: function () {
  58073. return this._buttonBack;
  58074. },
  58075. set: function (value) {
  58076. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58077. },
  58078. enumerable: true,
  58079. configurable: true
  58080. });
  58081. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58082. get: function () {
  58083. return this._buttonLB;
  58084. },
  58085. set: function (value) {
  58086. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58087. },
  58088. enumerable: true,
  58089. configurable: true
  58090. });
  58091. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58092. get: function () {
  58093. return this._buttonRB;
  58094. },
  58095. set: function (value) {
  58096. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58097. },
  58098. enumerable: true,
  58099. configurable: true
  58100. });
  58101. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58102. get: function () {
  58103. return this._buttonLeftStick;
  58104. },
  58105. set: function (value) {
  58106. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58107. },
  58108. enumerable: true,
  58109. configurable: true
  58110. });
  58111. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58112. get: function () {
  58113. return this._buttonRightStick;
  58114. },
  58115. set: function (value) {
  58116. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58117. },
  58118. enumerable: true,
  58119. configurable: true
  58120. });
  58121. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58122. get: function () {
  58123. return this._dPadUp;
  58124. },
  58125. set: function (value) {
  58126. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58127. },
  58128. enumerable: true,
  58129. configurable: true
  58130. });
  58131. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58132. get: function () {
  58133. return this._dPadDown;
  58134. },
  58135. set: function (value) {
  58136. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58137. },
  58138. enumerable: true,
  58139. configurable: true
  58140. });
  58141. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58142. get: function () {
  58143. return this._dPadLeft;
  58144. },
  58145. set: function (value) {
  58146. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58147. },
  58148. enumerable: true,
  58149. configurable: true
  58150. });
  58151. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58152. get: function () {
  58153. return this._dPadRight;
  58154. },
  58155. set: function (value) {
  58156. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58157. },
  58158. enumerable: true,
  58159. configurable: true
  58160. });
  58161. Xbox360Pad.prototype.update = function () {
  58162. _super.prototype.update.call(this);
  58163. if (this._isXboxOnePad) {
  58164. this.buttonA = this.browserGamepad.buttons[0].value;
  58165. this.buttonB = this.browserGamepad.buttons[1].value;
  58166. this.buttonX = this.browserGamepad.buttons[2].value;
  58167. this.buttonY = this.browserGamepad.buttons[3].value;
  58168. this.buttonLB = this.browserGamepad.buttons[4].value;
  58169. this.buttonRB = this.browserGamepad.buttons[5].value;
  58170. this.leftTrigger = this.browserGamepad.axes[2];
  58171. this.rightTrigger = this.browserGamepad.axes[5];
  58172. this.buttonBack = this.browserGamepad.buttons[9].value;
  58173. this.buttonStart = this.browserGamepad.buttons[8].value;
  58174. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58175. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58176. this.dPadUp = this.browserGamepad.buttons[11].value;
  58177. this.dPadDown = this.browserGamepad.buttons[12].value;
  58178. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58179. this.dPadRight = this.browserGamepad.buttons[14].value;
  58180. }
  58181. else {
  58182. this.buttonA = this.browserGamepad.buttons[0].value;
  58183. this.buttonB = this.browserGamepad.buttons[1].value;
  58184. this.buttonX = this.browserGamepad.buttons[2].value;
  58185. this.buttonY = this.browserGamepad.buttons[3].value;
  58186. this.buttonLB = this.browserGamepad.buttons[4].value;
  58187. this.buttonRB = this.browserGamepad.buttons[5].value;
  58188. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58189. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58190. this.buttonBack = this.browserGamepad.buttons[8].value;
  58191. this.buttonStart = this.browserGamepad.buttons[9].value;
  58192. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58193. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58194. this.dPadUp = this.browserGamepad.buttons[12].value;
  58195. this.dPadDown = this.browserGamepad.buttons[13].value;
  58196. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58197. this.dPadRight = this.browserGamepad.buttons[15].value;
  58198. }
  58199. };
  58200. Xbox360Pad.prototype.dispose = function () {
  58201. _super.prototype.dispose.call(this);
  58202. this.onButtonDownObservable.clear();
  58203. this.onButtonUpObservable.clear();
  58204. this.onPadDownObservable.clear();
  58205. this.onPadUpObservable.clear();
  58206. };
  58207. return Xbox360Pad;
  58208. }(BABYLON.Gamepad));
  58209. BABYLON.Xbox360Pad = Xbox360Pad;
  58210. })(BABYLON || (BABYLON = {}));
  58211. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58212. var BABYLON;
  58213. (function (BABYLON) {
  58214. var PoseEnabledControllerType;
  58215. (function (PoseEnabledControllerType) {
  58216. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58217. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58218. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58219. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58220. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58221. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58222. var PoseEnabledControllerHelper = /** @class */ (function () {
  58223. function PoseEnabledControllerHelper() {
  58224. }
  58225. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58226. // Oculus Touch
  58227. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58228. return new BABYLON.OculusTouchController(vrGamepad);
  58229. }
  58230. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58231. return new BABYLON.WindowsMotionController(vrGamepad);
  58232. }
  58233. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58234. return new BABYLON.ViveController(vrGamepad);
  58235. }
  58236. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58237. return new BABYLON.GearVRController(vrGamepad);
  58238. }
  58239. else {
  58240. return new BABYLON.GenericController(vrGamepad);
  58241. }
  58242. };
  58243. return PoseEnabledControllerHelper;
  58244. }());
  58245. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58246. var PoseEnabledController = /** @class */ (function (_super) {
  58247. __extends(PoseEnabledController, _super);
  58248. function PoseEnabledController(browserGamepad) {
  58249. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58250. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58251. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58252. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58253. // Represents device position and rotation in babylon space
  58254. _this.devicePosition = BABYLON.Vector3.Zero();
  58255. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58256. _this.deviceScaleFactor = 1;
  58257. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58258. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58259. _this._workingMatrix = BABYLON.Matrix.Identity();
  58260. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58261. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58262. _this.position = BABYLON.Vector3.Zero();
  58263. _this.rotationQuaternion = new BABYLON.Quaternion();
  58264. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58265. _this._calculatedRotation = new BABYLON.Quaternion();
  58266. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58267. return _this;
  58268. }
  58269. PoseEnabledController.prototype.update = function () {
  58270. _super.prototype.update.call(this);
  58271. var pose = this.browserGamepad.pose;
  58272. this.updateFromDevice(pose);
  58273. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58274. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58275. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58276. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58277. if (this._mesh) {
  58278. this._mesh.position.copyFrom(this.devicePosition);
  58279. if (this._mesh.rotationQuaternion) {
  58280. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58281. }
  58282. }
  58283. };
  58284. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58285. if (poseData) {
  58286. this.rawPose = poseData;
  58287. if (poseData.position) {
  58288. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58289. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58290. this._deviceRoomPosition.z *= -1;
  58291. }
  58292. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58293. this._calculatedPosition.addInPlace(this.position);
  58294. }
  58295. var pose = this.rawPose;
  58296. if (poseData.orientation && pose.orientation) {
  58297. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58298. if (this._mesh) {
  58299. if (this._mesh.getScene().useRightHandedSystem) {
  58300. this._deviceRoomRotationQuaternion.z *= -1;
  58301. this._deviceRoomRotationQuaternion.w *= -1;
  58302. }
  58303. else {
  58304. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58305. }
  58306. }
  58307. // if the camera is set, rotate to the camera's rotation
  58308. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58309. }
  58310. }
  58311. };
  58312. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58313. if (this._mesh) {
  58314. this._mesh.parent = null;
  58315. }
  58316. this._mesh = mesh;
  58317. if (this._poseControlledCamera) {
  58318. this._mesh.parent = this._poseControlledCamera;
  58319. }
  58320. if (!this._mesh.rotationQuaternion) {
  58321. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58322. }
  58323. };
  58324. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58325. this._poseControlledCamera = camera;
  58326. if (this._mesh) {
  58327. this._mesh.parent = this._poseControlledCamera;
  58328. }
  58329. };
  58330. PoseEnabledController.prototype.dispose = function () {
  58331. if (this._mesh) {
  58332. this._mesh.dispose();
  58333. }
  58334. this._mesh = null;
  58335. _super.prototype.dispose.call(this);
  58336. };
  58337. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58338. get: function () {
  58339. return this._mesh;
  58340. },
  58341. enumerable: true,
  58342. configurable: true
  58343. });
  58344. PoseEnabledController.prototype.getForwardRay = function (length) {
  58345. if (length === void 0) { length = 100; }
  58346. if (!this.mesh) {
  58347. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58348. }
  58349. var m = this.mesh.getWorldMatrix();
  58350. var origin = m.getTranslation();
  58351. var forward = new BABYLON.Vector3(0, 0, -1);
  58352. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58353. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58354. return new BABYLON.Ray(origin, direction, length);
  58355. };
  58356. return PoseEnabledController;
  58357. }(BABYLON.Gamepad));
  58358. BABYLON.PoseEnabledController = PoseEnabledController;
  58359. })(BABYLON || (BABYLON = {}));
  58360. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58361. var BABYLON;
  58362. (function (BABYLON) {
  58363. var WebVRController = /** @class */ (function (_super) {
  58364. __extends(WebVRController, _super);
  58365. function WebVRController(vrGamepad) {
  58366. var _this = _super.call(this, vrGamepad) || this;
  58367. // Observables
  58368. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58369. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58370. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58371. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58372. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58373. _this.pad = { x: 0, y: 0 };
  58374. // avoid GC, store state in a tmp object
  58375. _this._changes = {
  58376. pressChanged: false,
  58377. touchChanged: false,
  58378. valueChanged: false,
  58379. changed: false
  58380. };
  58381. _this._buttons = new Array(vrGamepad.buttons.length);
  58382. _this.hand = vrGamepad.hand;
  58383. return _this;
  58384. }
  58385. WebVRController.prototype.onButtonStateChange = function (callback) {
  58386. this._onButtonStateChange = callback;
  58387. };
  58388. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58389. get: function () {
  58390. return this._defaultModel;
  58391. },
  58392. enumerable: true,
  58393. configurable: true
  58394. });
  58395. WebVRController.prototype.update = function () {
  58396. _super.prototype.update.call(this);
  58397. for (var index = 0; index < this._buttons.length; index++) {
  58398. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58399. }
  58400. ;
  58401. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58402. this.pad.x = this.leftStick.x;
  58403. this.pad.y = this.leftStick.y;
  58404. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58405. }
  58406. };
  58407. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58408. if (!newState) {
  58409. newState = {
  58410. pressed: false,
  58411. touched: false,
  58412. value: 0
  58413. };
  58414. }
  58415. if (!currentState) {
  58416. this._buttons[buttonIndex] = {
  58417. pressed: newState.pressed,
  58418. touched: newState.touched,
  58419. value: newState.value
  58420. };
  58421. return;
  58422. }
  58423. this._checkChanges(newState, currentState);
  58424. if (this._changes.changed) {
  58425. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58426. this.handleButtonChange(buttonIndex, newState, this._changes);
  58427. }
  58428. this._buttons[buttonIndex].pressed = newState.pressed;
  58429. this._buttons[buttonIndex].touched = newState.touched;
  58430. // oculus triggers are never 0, thou not touched.
  58431. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58432. };
  58433. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58434. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58435. this._changes.touchChanged = newState.touched !== currentState.touched;
  58436. this._changes.valueChanged = newState.value !== currentState.value;
  58437. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58438. return this._changes;
  58439. };
  58440. WebVRController.prototype.dispose = function () {
  58441. _super.prototype.dispose.call(this);
  58442. this.onTriggerStateChangedObservable.clear();
  58443. this.onMainButtonStateChangedObservable.clear();
  58444. this.onSecondaryButtonStateChangedObservable.clear();
  58445. this.onPadStateChangedObservable.clear();
  58446. this.onPadValuesChangedObservable.clear();
  58447. };
  58448. return WebVRController;
  58449. }(BABYLON.PoseEnabledController));
  58450. BABYLON.WebVRController = WebVRController;
  58451. })(BABYLON || (BABYLON = {}));
  58452. //# sourceMappingURL=babylon.webVRController.js.map
  58453. var BABYLON;
  58454. (function (BABYLON) {
  58455. var OculusTouchController = /** @class */ (function (_super) {
  58456. __extends(OculusTouchController, _super);
  58457. function OculusTouchController(vrGamepad) {
  58458. var _this = _super.call(this, vrGamepad) || this;
  58459. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58460. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58461. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58462. return _this;
  58463. }
  58464. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58465. var _this = this;
  58466. var meshName;
  58467. // Hand
  58468. if (this.hand === 'left') {
  58469. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58470. }
  58471. else {
  58472. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58473. }
  58474. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58475. /*
  58476. Parent Mesh name: oculus_touch_left
  58477. - body
  58478. - trigger
  58479. - thumbstick
  58480. - grip
  58481. - button_y
  58482. - button_x
  58483. - button_enter
  58484. */
  58485. _this._defaultModel = newMeshes[1];
  58486. _this.attachToMesh(_this._defaultModel);
  58487. if (meshLoaded) {
  58488. meshLoaded(_this._defaultModel);
  58489. }
  58490. });
  58491. };
  58492. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58493. // helper getters for left and right hand.
  58494. get: function () {
  58495. if (this.hand === 'right') {
  58496. return this.onMainButtonStateChangedObservable;
  58497. }
  58498. else {
  58499. throw new Error('No A button on left hand');
  58500. }
  58501. },
  58502. enumerable: true,
  58503. configurable: true
  58504. });
  58505. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58506. get: function () {
  58507. if (this.hand === 'right') {
  58508. return this.onSecondaryButtonStateChangedObservable;
  58509. }
  58510. else {
  58511. throw new Error('No B button on left hand');
  58512. }
  58513. },
  58514. enumerable: true,
  58515. configurable: true
  58516. });
  58517. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58518. get: function () {
  58519. if (this.hand === 'left') {
  58520. return this.onMainButtonStateChangedObservable;
  58521. }
  58522. else {
  58523. throw new Error('No X button on right hand');
  58524. }
  58525. },
  58526. enumerable: true,
  58527. configurable: true
  58528. });
  58529. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58530. get: function () {
  58531. if (this.hand === 'left') {
  58532. return this.onSecondaryButtonStateChangedObservable;
  58533. }
  58534. else {
  58535. throw new Error('No Y button on right hand');
  58536. }
  58537. },
  58538. enumerable: true,
  58539. configurable: true
  58540. });
  58541. /*
  58542. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58543. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58544. 2) secondary trigger (same)
  58545. 3) A (right) X (left), touch, pressed = value
  58546. 4) B / Y
  58547. 5) thumb rest
  58548. */
  58549. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58550. var notifyObject = state; //{ state: state, changes: changes };
  58551. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58552. switch (buttonIdx) {
  58553. case 0:
  58554. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58555. return;
  58556. case 1:// index trigger
  58557. if (this._defaultModel) {
  58558. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58559. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58560. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58561. }
  58562. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58563. return;
  58564. case 2:// secondary trigger
  58565. if (this._defaultModel) {
  58566. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58567. }
  58568. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58569. return;
  58570. case 3:
  58571. if (this._defaultModel) {
  58572. if (notifyObject.pressed) {
  58573. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58574. }
  58575. else {
  58576. (this._defaultModel.getChildren()[1]).position.y = 0;
  58577. }
  58578. }
  58579. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58580. return;
  58581. case 4:
  58582. if (this._defaultModel) {
  58583. if (notifyObject.pressed) {
  58584. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58585. }
  58586. else {
  58587. (this._defaultModel.getChildren()[2]).position.y = 0;
  58588. }
  58589. }
  58590. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58591. return;
  58592. case 5:
  58593. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58594. return;
  58595. }
  58596. };
  58597. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58598. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58599. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58600. return OculusTouchController;
  58601. }(BABYLON.WebVRController));
  58602. BABYLON.OculusTouchController = OculusTouchController;
  58603. })(BABYLON || (BABYLON = {}));
  58604. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58605. var BABYLON;
  58606. (function (BABYLON) {
  58607. var ViveController = /** @class */ (function (_super) {
  58608. __extends(ViveController, _super);
  58609. function ViveController(vrGamepad) {
  58610. var _this = _super.call(this, vrGamepad) || this;
  58611. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58612. _this._invertLeftStickY = true;
  58613. return _this;
  58614. }
  58615. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58616. var _this = this;
  58617. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58618. /*
  58619. Parent Mesh name: ViveWand
  58620. - body
  58621. - r_gripper
  58622. - l_gripper
  58623. - menu_button
  58624. - system_button
  58625. - trackpad
  58626. - trigger
  58627. - LED
  58628. */
  58629. _this._defaultModel = newMeshes[1];
  58630. _this.attachToMesh(_this._defaultModel);
  58631. if (meshLoaded) {
  58632. meshLoaded(_this._defaultModel);
  58633. }
  58634. });
  58635. };
  58636. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58637. get: function () {
  58638. return this.onMainButtonStateChangedObservable;
  58639. },
  58640. enumerable: true,
  58641. configurable: true
  58642. });
  58643. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58644. get: function () {
  58645. return this.onMainButtonStateChangedObservable;
  58646. },
  58647. enumerable: true,
  58648. configurable: true
  58649. });
  58650. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58651. get: function () {
  58652. return this.onSecondaryButtonStateChangedObservable;
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. /**
  58658. * Vive mapping:
  58659. * 0: touchpad
  58660. * 1: trigger
  58661. * 2: left AND right buttons
  58662. * 3: menu button
  58663. */
  58664. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58665. var notifyObject = state; //{ state: state, changes: changes };
  58666. switch (buttonIdx) {
  58667. case 0:
  58668. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58669. return;
  58670. case 1:// index trigger
  58671. if (this._defaultModel) {
  58672. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58673. }
  58674. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58675. return;
  58676. case 2:// left AND right button
  58677. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58678. return;
  58679. case 3:
  58680. if (this._defaultModel) {
  58681. if (notifyObject.pressed) {
  58682. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58683. }
  58684. else {
  58685. (this._defaultModel.getChildren()[2]).position.y = 0;
  58686. }
  58687. }
  58688. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58689. return;
  58690. }
  58691. };
  58692. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58693. ViveController.MODEL_FILENAME = 'wand.babylon';
  58694. return ViveController;
  58695. }(BABYLON.WebVRController));
  58696. BABYLON.ViveController = ViveController;
  58697. })(BABYLON || (BABYLON = {}));
  58698. //# sourceMappingURL=babylon.viveController.js.map
  58699. var BABYLON;
  58700. (function (BABYLON) {
  58701. var GenericController = /** @class */ (function (_super) {
  58702. __extends(GenericController, _super);
  58703. function GenericController(vrGamepad) {
  58704. return _super.call(this, vrGamepad) || this;
  58705. }
  58706. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58707. var _this = this;
  58708. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58709. _this._defaultModel = newMeshes[1];
  58710. _this.attachToMesh(_this._defaultModel);
  58711. if (meshLoaded) {
  58712. meshLoaded(_this._defaultModel);
  58713. }
  58714. });
  58715. };
  58716. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58717. console.log("Button id: " + buttonIdx + "state: ");
  58718. console.dir(state);
  58719. };
  58720. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58721. GenericController.MODEL_FILENAME = 'generic.babylon';
  58722. return GenericController;
  58723. }(BABYLON.WebVRController));
  58724. BABYLON.GenericController = GenericController;
  58725. })(BABYLON || (BABYLON = {}));
  58726. //# sourceMappingURL=babylon.genericController.js.map
  58727. var BABYLON;
  58728. (function (BABYLON) {
  58729. var LoadedMeshInfo = /** @class */ (function () {
  58730. function LoadedMeshInfo() {
  58731. this.buttonMeshes = {};
  58732. this.axisMeshes = {};
  58733. }
  58734. return LoadedMeshInfo;
  58735. }());
  58736. var WindowsMotionController = /** @class */ (function (_super) {
  58737. __extends(WindowsMotionController, _super);
  58738. function WindowsMotionController(vrGamepad) {
  58739. var _this = _super.call(this, vrGamepad) || this;
  58740. _this._mapping = {
  58741. // Semantic button names
  58742. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58743. // A mapping of the button name to glTF model node name
  58744. // that should be transformed by button value.
  58745. buttonMeshNames: {
  58746. 'trigger': 'SELECT',
  58747. 'menu': 'MENU',
  58748. 'grip': 'GRASP',
  58749. 'thumbstick': 'THUMBSTICK_PRESS',
  58750. 'trackpad': 'TOUCHPAD_PRESS'
  58751. },
  58752. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58753. buttonObservableNames: {
  58754. 'trigger': 'onTriggerStateChangedObservable',
  58755. 'menu': 'onSecondaryButtonStateChangedObservable',
  58756. 'grip': 'onMainButtonStateChangedObservable',
  58757. 'thumbstick': 'onPadStateChangedObservable',
  58758. 'trackpad': 'onTrackpadChangedObservable'
  58759. },
  58760. // A mapping of the axis name to glTF model node name
  58761. // that should be transformed by axis value.
  58762. // This array mirrors the browserGamepad.axes array, such that
  58763. // the mesh corresponding to axis 0 is in this array index 0.
  58764. axisMeshNames: [
  58765. 'THUMBSTICK_X',
  58766. 'THUMBSTICK_Y',
  58767. 'TOUCHPAD_TOUCH_X',
  58768. 'TOUCHPAD_TOUCH_Y'
  58769. ],
  58770. pointingPoseMeshName: 'POINTING_POSE'
  58771. };
  58772. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58773. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58774. _this.trackpad = { x: 0, y: 0 };
  58775. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58776. _this._loadedMeshInfo = null;
  58777. return _this;
  58778. }
  58779. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58780. get: function () {
  58781. return this.onTriggerStateChangedObservable;
  58782. },
  58783. enumerable: true,
  58784. configurable: true
  58785. });
  58786. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58787. get: function () {
  58788. return this.onSecondaryButtonStateChangedObservable;
  58789. },
  58790. enumerable: true,
  58791. configurable: true
  58792. });
  58793. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58794. get: function () {
  58795. return this.onMainButtonStateChangedObservable;
  58796. },
  58797. enumerable: true,
  58798. configurable: true
  58799. });
  58800. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58801. get: function () {
  58802. return this.onPadStateChangedObservable;
  58803. },
  58804. enumerable: true,
  58805. configurable: true
  58806. });
  58807. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58808. get: function () {
  58809. return this.onTrackpadChangedObservable;
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58815. get: function () {
  58816. return this.onTrackpadValuesChangedObservable;
  58817. },
  58818. enumerable: true,
  58819. configurable: true
  58820. });
  58821. /**
  58822. * Called once per frame by the engine.
  58823. */
  58824. WindowsMotionController.prototype.update = function () {
  58825. _super.prototype.update.call(this);
  58826. // Only need to animate axes if there is a loaded mesh
  58827. if (this._loadedMeshInfo) {
  58828. if (this.browserGamepad.axes) {
  58829. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58830. this.trackpad.x = this.browserGamepad["axes"][2];
  58831. this.trackpad.y = this.browserGamepad["axes"][3];
  58832. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58833. }
  58834. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58835. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58836. }
  58837. }
  58838. }
  58839. };
  58840. /**
  58841. * Called once for each button that changed state since the last frame
  58842. * @param buttonIdx Which button index changed
  58843. * @param state New state of the button
  58844. * @param changes Which properties on the state changed since last frame
  58845. */
  58846. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58847. var buttonName = this._mapping.buttons[buttonIdx];
  58848. if (!buttonName) {
  58849. return;
  58850. }
  58851. // Only emit events for buttons that we know how to map from index to name
  58852. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58853. if (observable) {
  58854. observable.notifyObservers(state);
  58855. }
  58856. this.lerpButtonTransform(buttonName, state.value);
  58857. };
  58858. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58859. // If there is no loaded mesh, there is nothing to transform.
  58860. if (!this._loadedMeshInfo) {
  58861. return;
  58862. }
  58863. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58864. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58865. return;
  58866. }
  58867. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58868. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58869. };
  58870. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58871. if (!this._loadedMeshInfo) {
  58872. return;
  58873. }
  58874. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58875. if (!meshInfo) {
  58876. return;
  58877. }
  58878. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58879. return;
  58880. }
  58881. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58882. var lerpValue = axisValue * 0.5 + 0.5;
  58883. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58884. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58885. };
  58886. /**
  58887. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58888. * @param scene scene in which to add meshes
  58889. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58890. */
  58891. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58892. var _this = this;
  58893. if (forceDefault === void 0) { forceDefault = false; }
  58894. var path;
  58895. var filename;
  58896. // Checking if GLB loader is present
  58897. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58898. // Determine the device specific folder based on the ID suffix
  58899. var device = 'default';
  58900. if (this.id && !forceDefault) {
  58901. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58902. device = ((match && match[0]) || device);
  58903. }
  58904. // Hand
  58905. if (this.hand === 'left') {
  58906. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58907. }
  58908. else {
  58909. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58910. }
  58911. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58912. }
  58913. else {
  58914. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58915. path = BABYLON.GenericController.MODEL_BASE_URL;
  58916. filename = BABYLON.GenericController.MODEL_FILENAME;
  58917. }
  58918. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58919. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58920. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58921. if (!_this._loadedMeshInfo) {
  58922. return;
  58923. }
  58924. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58925. _this.attachToMesh(_this._defaultModel);
  58926. if (meshLoaded) {
  58927. meshLoaded(_this._defaultModel);
  58928. }
  58929. }, null, function (scene, message) {
  58930. BABYLON.Tools.Log(message);
  58931. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58932. if (!forceDefault) {
  58933. _this.initControllerMesh(scene, meshLoaded, true);
  58934. }
  58935. });
  58936. };
  58937. /**
  58938. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58939. * can be transformed by button presses and axes values, based on this._mapping.
  58940. *
  58941. * @param scene scene in which the meshes exist
  58942. * @param meshes list of meshes that make up the controller model to process
  58943. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58944. */
  58945. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58946. var loadedMeshInfo = null;
  58947. // Create a new mesh to contain the glTF hierarchy
  58948. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58949. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58950. var childMesh = null;
  58951. for (var i = 0; i < meshes.length; i++) {
  58952. var mesh = meshes[i];
  58953. if (!mesh.parent) {
  58954. // Exclude controller meshes from picking results
  58955. mesh.isPickable = false;
  58956. // Handle root node, attach to the new parentMesh
  58957. childMesh = mesh;
  58958. break;
  58959. }
  58960. }
  58961. if (childMesh) {
  58962. childMesh.setParent(parentMesh);
  58963. // Create our mesh info. Note that this method will always return non-null.
  58964. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58965. }
  58966. else {
  58967. BABYLON.Tools.Warn('Could not find root node in model file.');
  58968. }
  58969. return loadedMeshInfo;
  58970. };
  58971. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58972. var loadedMeshInfo = new LoadedMeshInfo();
  58973. var i;
  58974. loadedMeshInfo.rootNode = rootNode;
  58975. // Reset the caches
  58976. loadedMeshInfo.buttonMeshes = {};
  58977. loadedMeshInfo.axisMeshes = {};
  58978. // Button Meshes
  58979. for (i = 0; i < this._mapping.buttons.length; i++) {
  58980. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58981. if (!buttonMeshName) {
  58982. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58983. continue;
  58984. }
  58985. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58986. if (!buttonMesh) {
  58987. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58988. continue;
  58989. }
  58990. var buttonMeshInfo = {
  58991. index: i,
  58992. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58993. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58994. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58995. };
  58996. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58997. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58998. }
  58999. else {
  59000. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  59001. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  59002. '(VALUE: ' + !!buttonMeshInfo.value +
  59003. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  59004. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  59005. ')');
  59006. }
  59007. }
  59008. // Axis Meshes
  59009. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  59010. var axisMeshName = this._mapping.axisMeshNames[i];
  59011. if (!axisMeshName) {
  59012. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  59013. continue;
  59014. }
  59015. var axisMesh = getChildByName(rootNode, axisMeshName);
  59016. if (!axisMesh) {
  59017. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59018. continue;
  59019. }
  59020. var axisMeshInfo = {
  59021. index: i,
  59022. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59023. min: getImmediateChildByName(axisMesh, 'MIN'),
  59024. max: getImmediateChildByName(axisMesh, 'MAX')
  59025. };
  59026. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59027. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59028. }
  59029. else {
  59030. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59031. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59032. '(VALUE: ' + !!axisMeshInfo.value +
  59033. ', MIN: ' + !!axisMeshInfo.min +
  59034. ', MAX:' + !!axisMeshInfo.max +
  59035. ')');
  59036. }
  59037. }
  59038. // Pointing Ray
  59039. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59040. if (!loadedMeshInfo.pointingPoseNode) {
  59041. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59042. }
  59043. return loadedMeshInfo;
  59044. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59045. function getChildByName(node, name) {
  59046. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59047. }
  59048. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59049. function getImmediateChildByName(node, name) {
  59050. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59051. }
  59052. };
  59053. WindowsMotionController.prototype.getForwardRay = function (length) {
  59054. if (length === void 0) { length = 100; }
  59055. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59056. return _super.prototype.getForwardRay.call(this, length);
  59057. }
  59058. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59059. var origin = m.getTranslation();
  59060. var forward = new BABYLON.Vector3(0, 0, -1);
  59061. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59062. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59063. return new BABYLON.Ray(origin, direction, length);
  59064. };
  59065. WindowsMotionController.prototype.dispose = function () {
  59066. _super.prototype.dispose.call(this);
  59067. this.onTrackpadChangedObservable.clear();
  59068. };
  59069. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59070. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59071. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59072. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59073. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59074. return WindowsMotionController;
  59075. }(BABYLON.WebVRController));
  59076. BABYLON.WindowsMotionController = WindowsMotionController;
  59077. })(BABYLON || (BABYLON = {}));
  59078. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59079. var BABYLON;
  59080. (function (BABYLON) {
  59081. var GearVRController = /** @class */ (function (_super) {
  59082. __extends(GearVRController, _super);
  59083. function GearVRController(vrGamepad) {
  59084. var _this = _super.call(this, vrGamepad) || this;
  59085. _this._buttonIndexToObservableNameMap = [
  59086. 'onTrackpadChangedObservable',
  59087. 'onTriggerStateChangedObservable' // Trigger
  59088. ];
  59089. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59090. return _this;
  59091. }
  59092. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59093. var _this = this;
  59094. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59095. _this._defaultModel = newMeshes[1];
  59096. _this.attachToMesh(_this._defaultModel);
  59097. if (meshLoaded) {
  59098. meshLoaded(_this._defaultModel);
  59099. }
  59100. });
  59101. };
  59102. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59103. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59104. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59105. // Only emit events for buttons that we know how to map from index to observable
  59106. var observable = this[observableName];
  59107. if (observable) {
  59108. observable.notifyObservers(state);
  59109. }
  59110. }
  59111. };
  59112. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59113. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59114. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59115. return GearVRController;
  59116. }(BABYLON.WebVRController));
  59117. BABYLON.GearVRController = GearVRController;
  59118. })(BABYLON || (BABYLON = {}));
  59119. //# sourceMappingURL=babylon.gearVRController.js.map
  59120. var BABYLON;
  59121. (function (BABYLON) {
  59122. var FollowCamera = /** @class */ (function (_super) {
  59123. __extends(FollowCamera, _super);
  59124. function FollowCamera(name, position, scene, lockedTarget) {
  59125. if (lockedTarget === void 0) { lockedTarget = null; }
  59126. var _this = _super.call(this, name, position, scene) || this;
  59127. _this.radius = 12;
  59128. _this.rotationOffset = 0;
  59129. _this.heightOffset = 4;
  59130. _this.cameraAcceleration = 0.05;
  59131. _this.maxCameraSpeed = 20;
  59132. _this.lockedTarget = lockedTarget;
  59133. return _this;
  59134. }
  59135. FollowCamera.prototype.getRadians = function (degrees) {
  59136. return degrees * Math.PI / 180;
  59137. };
  59138. FollowCamera.prototype.follow = function (cameraTarget) {
  59139. if (!cameraTarget)
  59140. return;
  59141. var yRotation;
  59142. if (cameraTarget.rotationQuaternion) {
  59143. var rotMatrix = new BABYLON.Matrix();
  59144. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59145. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59146. }
  59147. else {
  59148. yRotation = cameraTarget.rotation.y;
  59149. }
  59150. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59151. var targetPosition = cameraTarget.getAbsolutePosition();
  59152. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59153. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59154. var dx = targetX - this.position.x;
  59155. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59156. var dz = (targetZ) - this.position.z;
  59157. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59158. var vy = dy * this.cameraAcceleration;
  59159. var vz = dz * this.cameraAcceleration * 2;
  59160. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59161. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59162. }
  59163. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59164. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59165. }
  59166. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59167. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59168. }
  59169. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59170. this.setTarget(targetPosition);
  59171. };
  59172. FollowCamera.prototype._checkInputs = function () {
  59173. _super.prototype._checkInputs.call(this);
  59174. if (this.lockedTarget) {
  59175. this.follow(this.lockedTarget);
  59176. }
  59177. };
  59178. FollowCamera.prototype.getClassName = function () {
  59179. return "FollowCamera";
  59180. };
  59181. __decorate([
  59182. BABYLON.serialize()
  59183. ], FollowCamera.prototype, "radius", void 0);
  59184. __decorate([
  59185. BABYLON.serialize()
  59186. ], FollowCamera.prototype, "rotationOffset", void 0);
  59187. __decorate([
  59188. BABYLON.serialize()
  59189. ], FollowCamera.prototype, "heightOffset", void 0);
  59190. __decorate([
  59191. BABYLON.serialize()
  59192. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59193. __decorate([
  59194. BABYLON.serialize()
  59195. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59196. __decorate([
  59197. BABYLON.serializeAsMeshReference("lockedTargetId")
  59198. ], FollowCamera.prototype, "lockedTarget", void 0);
  59199. return FollowCamera;
  59200. }(BABYLON.TargetCamera));
  59201. BABYLON.FollowCamera = FollowCamera;
  59202. var ArcFollowCamera = /** @class */ (function (_super) {
  59203. __extends(ArcFollowCamera, _super);
  59204. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59205. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59206. _this.alpha = alpha;
  59207. _this.beta = beta;
  59208. _this.radius = radius;
  59209. _this.target = target;
  59210. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59211. _this.follow();
  59212. return _this;
  59213. }
  59214. ArcFollowCamera.prototype.follow = function () {
  59215. if (!this.target) {
  59216. return;
  59217. }
  59218. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59219. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59220. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59221. var targetPosition = this.target.getAbsolutePosition();
  59222. this.position = targetPosition.add(this._cartesianCoordinates);
  59223. this.setTarget(targetPosition);
  59224. };
  59225. ArcFollowCamera.prototype._checkInputs = function () {
  59226. _super.prototype._checkInputs.call(this);
  59227. this.follow();
  59228. };
  59229. ArcFollowCamera.prototype.getClassName = function () {
  59230. return "ArcFollowCamera";
  59231. };
  59232. return ArcFollowCamera;
  59233. }(BABYLON.TargetCamera));
  59234. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59235. })(BABYLON || (BABYLON = {}));
  59236. //# sourceMappingURL=babylon.followCamera.js.map
  59237. var BABYLON;
  59238. (function (BABYLON) {
  59239. // We're mainly based on the logic defined into the FreeCamera code
  59240. var UniversalCamera = /** @class */ (function (_super) {
  59241. __extends(UniversalCamera, _super);
  59242. //-- end properties for backward compatibility for inputs
  59243. function UniversalCamera(name, position, scene) {
  59244. var _this = _super.call(this, name, position, scene) || this;
  59245. _this.inputs.addGamepad();
  59246. return _this;
  59247. }
  59248. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59249. //-- Begin properties for backward compatibility for inputs
  59250. get: function () {
  59251. var gamepad = this.inputs.attached["gamepad"];
  59252. if (gamepad)
  59253. return gamepad.gamepadAngularSensibility;
  59254. return 0;
  59255. },
  59256. set: function (value) {
  59257. var gamepad = this.inputs.attached["gamepad"];
  59258. if (gamepad)
  59259. gamepad.gamepadAngularSensibility = value;
  59260. },
  59261. enumerable: true,
  59262. configurable: true
  59263. });
  59264. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59265. get: function () {
  59266. var gamepad = this.inputs.attached["gamepad"];
  59267. if (gamepad)
  59268. return gamepad.gamepadMoveSensibility;
  59269. return 0;
  59270. },
  59271. set: function (value) {
  59272. var gamepad = this.inputs.attached["gamepad"];
  59273. if (gamepad)
  59274. gamepad.gamepadMoveSensibility = value;
  59275. },
  59276. enumerable: true,
  59277. configurable: true
  59278. });
  59279. UniversalCamera.prototype.getClassName = function () {
  59280. return "UniversalCamera";
  59281. };
  59282. return UniversalCamera;
  59283. }(BABYLON.TouchCamera));
  59284. BABYLON.UniversalCamera = UniversalCamera;
  59285. })(BABYLON || (BABYLON = {}));
  59286. //# sourceMappingURL=babylon.universalCamera.js.map
  59287. var BABYLON;
  59288. (function (BABYLON) {
  59289. // We're mainly based on the logic defined into the FreeCamera code
  59290. var GamepadCamera = /** @class */ (function (_super) {
  59291. __extends(GamepadCamera, _super);
  59292. //-- end properties for backward compatibility for inputs
  59293. function GamepadCamera(name, position, scene) {
  59294. return _super.call(this, name, position, scene) || this;
  59295. }
  59296. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59297. //-- Begin properties for backward compatibility for inputs
  59298. get: function () {
  59299. var gamepad = this.inputs.attached["gamepad"];
  59300. if (gamepad)
  59301. return gamepad.gamepadAngularSensibility;
  59302. return 0;
  59303. },
  59304. set: function (value) {
  59305. var gamepad = this.inputs.attached["gamepad"];
  59306. if (gamepad)
  59307. gamepad.gamepadAngularSensibility = value;
  59308. },
  59309. enumerable: true,
  59310. configurable: true
  59311. });
  59312. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59313. get: function () {
  59314. var gamepad = this.inputs.attached["gamepad"];
  59315. if (gamepad)
  59316. return gamepad.gamepadMoveSensibility;
  59317. return 0;
  59318. },
  59319. set: function (value) {
  59320. var gamepad = this.inputs.attached["gamepad"];
  59321. if (gamepad)
  59322. gamepad.gamepadMoveSensibility = value;
  59323. },
  59324. enumerable: true,
  59325. configurable: true
  59326. });
  59327. GamepadCamera.prototype.getClassName = function () {
  59328. return "GamepadCamera";
  59329. };
  59330. return GamepadCamera;
  59331. }(BABYLON.UniversalCamera));
  59332. BABYLON.GamepadCamera = GamepadCamera;
  59333. })(BABYLON || (BABYLON = {}));
  59334. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59335. var BABYLON;
  59336. (function (BABYLON) {
  59337. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59338. function PostProcessRenderPipelineManager() {
  59339. this._renderPipelines = {};
  59340. }
  59341. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59342. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59343. };
  59344. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59345. if (unique === void 0) { unique = false; }
  59346. var renderPipeline = this._renderPipelines[renderPipelineName];
  59347. if (!renderPipeline) {
  59348. return;
  59349. }
  59350. renderPipeline._attachCameras(cameras, unique);
  59351. };
  59352. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59353. var renderPipeline = this._renderPipelines[renderPipelineName];
  59354. if (!renderPipeline) {
  59355. return;
  59356. }
  59357. renderPipeline._detachCameras(cameras);
  59358. };
  59359. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59360. var renderPipeline = this._renderPipelines[renderPipelineName];
  59361. if (!renderPipeline) {
  59362. return;
  59363. }
  59364. renderPipeline._enableEffect(renderEffectName, cameras);
  59365. };
  59366. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59367. var renderPipeline = this._renderPipelines[renderPipelineName];
  59368. if (!renderPipeline) {
  59369. return;
  59370. }
  59371. renderPipeline._disableEffect(renderEffectName, cameras);
  59372. };
  59373. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59374. var renderPipeline = this._renderPipelines[renderPipelineName];
  59375. if (!renderPipeline) {
  59376. return;
  59377. }
  59378. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59379. };
  59380. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59381. var renderPipeline = this._renderPipelines[renderPipelineName];
  59382. if (!renderPipeline) {
  59383. return;
  59384. }
  59385. renderPipeline._disableDisplayOnlyPass(cameras);
  59386. };
  59387. PostProcessRenderPipelineManager.prototype.update = function () {
  59388. for (var renderPipelineName in this._renderPipelines) {
  59389. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59390. var pipeline = this._renderPipelines[renderPipelineName];
  59391. if (!pipeline.isSupported) {
  59392. pipeline.dispose();
  59393. delete this._renderPipelines[renderPipelineName];
  59394. }
  59395. else {
  59396. pipeline._update();
  59397. }
  59398. }
  59399. }
  59400. };
  59401. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59402. for (var renderPipelineName in this._renderPipelines) {
  59403. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59404. var pipeline = this._renderPipelines[renderPipelineName];
  59405. pipeline._rebuild();
  59406. }
  59407. }
  59408. };
  59409. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59410. for (var renderPipelineName in this._renderPipelines) {
  59411. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59412. var pipeline = this._renderPipelines[renderPipelineName];
  59413. pipeline.dispose();
  59414. }
  59415. }
  59416. };
  59417. return PostProcessRenderPipelineManager;
  59418. }());
  59419. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59420. })(BABYLON || (BABYLON = {}));
  59421. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59422. var BABYLON;
  59423. (function (BABYLON) {
  59424. var PostProcessRenderPass = /** @class */ (function () {
  59425. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59426. this._refCount = 0;
  59427. this._name = name;
  59428. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59429. this.setRenderList(renderList);
  59430. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59431. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59432. this._scene = scene;
  59433. this._renderList = renderList;
  59434. }
  59435. // private
  59436. PostProcessRenderPass.prototype._incRefCount = function () {
  59437. if (this._refCount === 0) {
  59438. this._scene.customRenderTargets.push(this._renderTexture);
  59439. }
  59440. return ++this._refCount;
  59441. };
  59442. PostProcessRenderPass.prototype._decRefCount = function () {
  59443. this._refCount--;
  59444. if (this._refCount <= 0) {
  59445. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59446. }
  59447. return this._refCount;
  59448. };
  59449. PostProcessRenderPass.prototype._update = function () {
  59450. this.setRenderList(this._renderList);
  59451. };
  59452. // public
  59453. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59454. this._renderTexture.renderList = renderList;
  59455. };
  59456. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59457. return this._renderTexture;
  59458. };
  59459. return PostProcessRenderPass;
  59460. }());
  59461. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59462. })(BABYLON || (BABYLON = {}));
  59463. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59464. var BABYLON;
  59465. (function (BABYLON) {
  59466. var PostProcessRenderEffect = /** @class */ (function () {
  59467. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59468. this._name = name;
  59469. this._singleInstance = singleInstance || true;
  59470. this._getPostProcess = getPostProcess;
  59471. this._cameras = {};
  59472. this._indicesForCamera = {};
  59473. this._postProcesses = {};
  59474. this._renderPasses = {};
  59475. this._renderEffectAsPasses = {};
  59476. }
  59477. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59478. get: function () {
  59479. for (var index in this._postProcesses) {
  59480. if (!this._postProcesses[index].isSupported) {
  59481. return false;
  59482. }
  59483. }
  59484. return true;
  59485. },
  59486. enumerable: true,
  59487. configurable: true
  59488. });
  59489. PostProcessRenderEffect.prototype._update = function () {
  59490. for (var renderPassName in this._renderPasses) {
  59491. this._renderPasses[renderPassName]._update();
  59492. }
  59493. };
  59494. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59495. this._renderPasses[renderPass._name] = renderPass;
  59496. this._linkParameters();
  59497. };
  59498. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59499. delete this._renderPasses[renderPass._name];
  59500. this._linkParameters();
  59501. };
  59502. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59503. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59504. this._linkParameters();
  59505. };
  59506. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59507. for (var renderPassName in this._renderPasses) {
  59508. if (renderPassName === passName) {
  59509. return this._renderPasses[passName];
  59510. }
  59511. }
  59512. return null;
  59513. };
  59514. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59515. this._renderPasses = {};
  59516. this._linkParameters();
  59517. };
  59518. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59519. var cameraKey;
  59520. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59521. if (!cams) {
  59522. return;
  59523. }
  59524. for (var i = 0; i < cams.length; i++) {
  59525. var camera = cams[i];
  59526. var cameraName = camera.name;
  59527. if (this._singleInstance) {
  59528. cameraKey = 0;
  59529. }
  59530. else {
  59531. cameraKey = cameraName;
  59532. }
  59533. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59534. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59535. if (!this._indicesForCamera[cameraName]) {
  59536. this._indicesForCamera[cameraName] = [];
  59537. }
  59538. this._indicesForCamera[cameraName].push(index);
  59539. if (!this._cameras[cameraName]) {
  59540. this._cameras[cameraName] = camera;
  59541. }
  59542. for (var passName in this._renderPasses) {
  59543. this._renderPasses[passName]._incRefCount();
  59544. }
  59545. }
  59546. this._linkParameters();
  59547. };
  59548. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59549. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59550. if (!cams) {
  59551. return;
  59552. }
  59553. for (var i = 0; i < cams.length; i++) {
  59554. var camera = cams[i];
  59555. var cameraName = camera.name;
  59556. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59557. if (this._cameras[cameraName]) {
  59558. //this._indicesForCamera.splice(index, 1);
  59559. this._cameras[cameraName] = null;
  59560. }
  59561. for (var passName in this._renderPasses) {
  59562. this._renderPasses[passName]._decRefCount();
  59563. }
  59564. }
  59565. };
  59566. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59567. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59568. if (!cams) {
  59569. return;
  59570. }
  59571. for (var i = 0; i < cams.length; i++) {
  59572. var camera = cams[i];
  59573. var cameraName = camera.name;
  59574. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59575. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59576. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59577. }
  59578. }
  59579. for (var passName in this._renderPasses) {
  59580. this._renderPasses[passName]._incRefCount();
  59581. }
  59582. }
  59583. };
  59584. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59585. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59586. if (!cams) {
  59587. return;
  59588. }
  59589. for (var i = 0; i < cams.length; i++) {
  59590. var camera = cams[i];
  59591. var cameraName = camera.Name;
  59592. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59593. for (var passName in this._renderPasses) {
  59594. this._renderPasses[passName]._decRefCount();
  59595. }
  59596. }
  59597. };
  59598. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59599. if (this._singleInstance) {
  59600. return this._postProcesses[0];
  59601. }
  59602. else {
  59603. if (!camera) {
  59604. return null;
  59605. }
  59606. return this._postProcesses[camera.name];
  59607. }
  59608. };
  59609. PostProcessRenderEffect.prototype._linkParameters = function () {
  59610. var _this = this;
  59611. for (var index in this._postProcesses) {
  59612. if (this.applyParameters) {
  59613. this.applyParameters(this._postProcesses[index]);
  59614. }
  59615. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59616. _this._linkTextures(effect);
  59617. });
  59618. }
  59619. };
  59620. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59621. for (var renderPassName in this._renderPasses) {
  59622. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59623. }
  59624. for (var renderEffectName in this._renderEffectAsPasses) {
  59625. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59626. }
  59627. };
  59628. return PostProcessRenderEffect;
  59629. }());
  59630. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59631. })(BABYLON || (BABYLON = {}));
  59632. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59633. var BABYLON;
  59634. (function (BABYLON) {
  59635. var PostProcessRenderPipeline = /** @class */ (function () {
  59636. function PostProcessRenderPipeline(engine, name) {
  59637. this._engine = engine;
  59638. this._name = name;
  59639. this._renderEffects = {};
  59640. this._renderEffectsForIsolatedPass = new Array();
  59641. this._cameras = [];
  59642. }
  59643. PostProcessRenderPipeline.prototype.getClassName = function () {
  59644. return "PostProcessRenderPipeline";
  59645. };
  59646. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59647. get: function () {
  59648. for (var renderEffectName in this._renderEffects) {
  59649. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59650. if (!this._renderEffects[renderEffectName].isSupported) {
  59651. return false;
  59652. }
  59653. }
  59654. }
  59655. return true;
  59656. },
  59657. enumerable: true,
  59658. configurable: true
  59659. });
  59660. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59661. this._renderEffects[renderEffect._name] = renderEffect;
  59662. };
  59663. // private
  59664. PostProcessRenderPipeline.prototype._rebuild = function () {
  59665. };
  59666. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59667. var renderEffects = this._renderEffects[renderEffectName];
  59668. if (!renderEffects) {
  59669. return;
  59670. }
  59671. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59672. };
  59673. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59674. var renderEffects = this._renderEffects[renderEffectName];
  59675. if (!renderEffects) {
  59676. return;
  59677. }
  59678. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59679. };
  59680. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59682. if (!cams) {
  59683. return;
  59684. }
  59685. var indicesToDelete = [];
  59686. var i;
  59687. for (i = 0; i < cams.length; i++) {
  59688. var camera = cams[i];
  59689. var cameraName = camera.name;
  59690. if (this._cameras.indexOf(camera) === -1) {
  59691. this._cameras[cameraName] = camera;
  59692. }
  59693. else if (unique) {
  59694. indicesToDelete.push(i);
  59695. }
  59696. }
  59697. for (i = 0; i < indicesToDelete.length; i++) {
  59698. cameras.splice(indicesToDelete[i], 1);
  59699. }
  59700. for (var renderEffectName in this._renderEffects) {
  59701. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59702. this._renderEffects[renderEffectName]._attachCameras(cams);
  59703. }
  59704. }
  59705. };
  59706. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59707. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59708. if (!cams) {
  59709. return;
  59710. }
  59711. for (var renderEffectName in this._renderEffects) {
  59712. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59713. this._renderEffects[renderEffectName]._detachCameras(cams);
  59714. }
  59715. }
  59716. for (var i = 0; i < cams.length; i++) {
  59717. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59718. }
  59719. };
  59720. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59721. var _this = this;
  59722. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59723. if (!cams) {
  59724. return;
  59725. }
  59726. var pass = null;
  59727. var renderEffectName;
  59728. for (renderEffectName in this._renderEffects) {
  59729. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59730. pass = this._renderEffects[renderEffectName].getPass(passName);
  59731. if (pass != null) {
  59732. break;
  59733. }
  59734. }
  59735. }
  59736. if (pass === null) {
  59737. return;
  59738. }
  59739. for (renderEffectName in this._renderEffects) {
  59740. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59741. this._renderEffects[renderEffectName]._disable(cams);
  59742. }
  59743. }
  59744. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59745. for (var i = 0; i < cams.length; i++) {
  59746. var camera = cams[i];
  59747. var cameraName = camera.name;
  59748. 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); });
  59749. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59750. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59751. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59752. }
  59753. };
  59754. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59755. var _this = this;
  59756. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59757. if (!cams) {
  59758. return;
  59759. }
  59760. for (var i = 0; i < cams.length; i++) {
  59761. var camera = cams[i];
  59762. var cameraName = camera.name;
  59763. 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); });
  59764. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59765. }
  59766. for (var renderEffectName in this._renderEffects) {
  59767. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59768. this._renderEffects[renderEffectName]._enable(cams);
  59769. }
  59770. }
  59771. };
  59772. PostProcessRenderPipeline.prototype._update = function () {
  59773. for (var renderEffectName in this._renderEffects) {
  59774. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59775. this._renderEffects[renderEffectName]._update();
  59776. }
  59777. }
  59778. for (var i = 0; i < this._cameras.length; i++) {
  59779. var cameraName = this._cameras[i].name;
  59780. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59781. this._renderEffectsForIsolatedPass[cameraName]._update();
  59782. }
  59783. }
  59784. };
  59785. PostProcessRenderPipeline.prototype._reset = function () {
  59786. this._renderEffects = {};
  59787. this._renderEffectsForIsolatedPass = new Array();
  59788. };
  59789. PostProcessRenderPipeline.prototype.dispose = function () {
  59790. // Must be implemented by children
  59791. };
  59792. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59793. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59794. __decorate([
  59795. BABYLON.serialize()
  59796. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59797. return PostProcessRenderPipeline;
  59798. }());
  59799. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59800. })(BABYLON || (BABYLON = {}));
  59801. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59802. var BABYLON;
  59803. (function (BABYLON) {
  59804. var DepthRenderer = /** @class */ (function () {
  59805. function DepthRenderer(scene, type) {
  59806. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59807. var _this = this;
  59808. this._scene = scene;
  59809. var engine = scene.getEngine();
  59810. // Render target
  59811. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59812. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59813. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59814. this._depthMap.refreshRate = 1;
  59815. this._depthMap.renderParticles = false;
  59816. this._depthMap.renderList = null;
  59817. // set default depth value to 1.0 (far away)
  59818. this._depthMap.onClearObservable.add(function (engine) {
  59819. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59820. });
  59821. // Custom render function
  59822. var renderSubMesh = function (subMesh) {
  59823. var mesh = subMesh.getRenderingMesh();
  59824. var scene = _this._scene;
  59825. var engine = scene.getEngine();
  59826. var material = subMesh.getMaterial();
  59827. if (!material) {
  59828. return;
  59829. }
  59830. // Culling and reverse (right handed system)
  59831. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59832. // Managing instances
  59833. var batch = mesh._getInstancesRenderList(subMesh._id);
  59834. if (batch.mustReturn) {
  59835. return;
  59836. }
  59837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59838. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59839. engine.enableEffect(_this._effect);
  59840. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59841. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59842. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59843. // Alpha test
  59844. if (material && material.needAlphaTesting()) {
  59845. var alphaTexture = material.getAlphaTestTexture();
  59846. if (alphaTexture) {
  59847. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59848. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59849. }
  59850. }
  59851. // Bones
  59852. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59853. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59854. }
  59855. // Draw
  59856. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59857. }
  59858. };
  59859. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59860. var index;
  59861. if (depthOnlySubMeshes.length) {
  59862. engine.setColorWrite(false);
  59863. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59864. renderSubMesh(depthOnlySubMeshes.data[index]);
  59865. }
  59866. engine.setColorWrite(true);
  59867. }
  59868. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59869. renderSubMesh(opaqueSubMeshes.data[index]);
  59870. }
  59871. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59872. renderSubMesh(alphaTestSubMeshes.data[index]);
  59873. }
  59874. };
  59875. }
  59876. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59877. var material = subMesh.getMaterial();
  59878. if (material.disableDepthWrite) {
  59879. return false;
  59880. }
  59881. var defines = [];
  59882. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59883. var mesh = subMesh.getMesh();
  59884. // Alpha test
  59885. if (material && material.needAlphaTesting()) {
  59886. defines.push("#define ALPHATEST");
  59887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59888. attribs.push(BABYLON.VertexBuffer.UVKind);
  59889. defines.push("#define UV1");
  59890. }
  59891. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59893. defines.push("#define UV2");
  59894. }
  59895. }
  59896. // Bones
  59897. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59900. if (mesh.numBoneInfluencers > 4) {
  59901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59903. }
  59904. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59905. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59906. }
  59907. else {
  59908. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59909. }
  59910. // Instances
  59911. if (useInstances) {
  59912. defines.push("#define INSTANCES");
  59913. attribs.push("world0");
  59914. attribs.push("world1");
  59915. attribs.push("world2");
  59916. attribs.push("world3");
  59917. }
  59918. // Get correct effect
  59919. var join = defines.join("\n");
  59920. if (this._cachedDefines !== join) {
  59921. this._cachedDefines = join;
  59922. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59923. }
  59924. return this._effect.isReady();
  59925. };
  59926. DepthRenderer.prototype.getDepthMap = function () {
  59927. return this._depthMap;
  59928. };
  59929. // Methods
  59930. DepthRenderer.prototype.dispose = function () {
  59931. this._depthMap.dispose();
  59932. };
  59933. return DepthRenderer;
  59934. }());
  59935. BABYLON.DepthRenderer = DepthRenderer;
  59936. })(BABYLON || (BABYLON = {}));
  59937. //# sourceMappingURL=babylon.depthRenderer.js.map
  59938. var BABYLON;
  59939. (function (BABYLON) {
  59940. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59941. __extends(SSAORenderingPipeline, _super);
  59942. /**
  59943. * @constructor
  59944. * @param {string} name - The rendering pipeline name
  59945. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59946. * @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 }
  59947. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59948. */
  59949. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59950. var _this = _super.call(this, scene.getEngine(), name) || this;
  59951. // Members
  59952. /**
  59953. * The PassPostProcess id in the pipeline that contains the original scene color
  59954. * @type {string}
  59955. */
  59956. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59957. /**
  59958. * The SSAO PostProcess id in the pipeline
  59959. * @type {string}
  59960. */
  59961. _this.SSAORenderEffect = "SSAORenderEffect";
  59962. /**
  59963. * The horizontal blur PostProcess id in the pipeline
  59964. * @type {string}
  59965. */
  59966. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59967. /**
  59968. * The vertical blur PostProcess id in the pipeline
  59969. * @type {string}
  59970. */
  59971. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59972. /**
  59973. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59974. * @type {string}
  59975. */
  59976. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59977. /**
  59978. * The output strength of the SSAO post-process. Default value is 1.0.
  59979. * @type {number}
  59980. */
  59981. _this.totalStrength = 1.0;
  59982. /**
  59983. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59984. * @type {number}
  59985. */
  59986. _this.radius = 0.0001;
  59987. /**
  59988. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59989. * Must not be equal to fallOff and superior to fallOff.
  59990. * Default value is 0.975
  59991. * @type {number}
  59992. */
  59993. _this.area = 0.0075;
  59994. /**
  59995. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59996. * Must not be equal to area and inferior to area.
  59997. * Default value is 0.0
  59998. * @type {number}
  59999. */
  60000. _this.fallOff = 0.000001;
  60001. /**
  60002. * The base color of the SSAO post-process
  60003. * The final result is "base + ssao" between [0, 1]
  60004. * @type {number}
  60005. */
  60006. _this.base = 0.5;
  60007. _this._firstUpdate = true;
  60008. _this._scene = scene;
  60009. // Set up assets
  60010. _this._createRandomTexture();
  60011. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60012. var ssaoRatio = ratio.ssaoRatio || ratio;
  60013. var combineRatio = ratio.combineRatio || ratio;
  60014. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60015. _this._createSSAOPostProcess(ssaoRatio);
  60016. _this._createBlurPostProcess(ssaoRatio);
  60017. _this._createSSAOCombinePostProcess(combineRatio);
  60018. // Set up pipeline
  60019. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60024. // Finish
  60025. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60026. if (cameras)
  60027. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60028. return _this;
  60029. }
  60030. // Public Methods
  60031. /**
  60032. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60033. */
  60034. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60035. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60036. for (var i = 0; i < this._scene.cameras.length; i++) {
  60037. var camera = this._scene.cameras[i];
  60038. this._originalColorPostProcess.dispose(camera);
  60039. this._ssaoPostProcess.dispose(camera);
  60040. this._blurHPostProcess.dispose(camera);
  60041. this._blurVPostProcess.dispose(camera);
  60042. this._ssaoCombinePostProcess.dispose(camera);
  60043. }
  60044. this._randomTexture.dispose();
  60045. if (disableDepthRender)
  60046. this._scene.disableDepthRenderer();
  60047. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60048. _super.prototype.dispose.call(this);
  60049. };
  60050. // Private Methods
  60051. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60052. var _this = this;
  60053. var size = 16;
  60054. 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);
  60055. 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);
  60056. this._blurHPostProcess.onActivateObservable.add(function () {
  60057. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60058. _this._blurHPostProcess.kernel = size * dw;
  60059. });
  60060. this._blurVPostProcess.onActivateObservable.add(function () {
  60061. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60062. _this._blurVPostProcess.kernel = size * dw;
  60063. });
  60064. };
  60065. SSAORenderingPipeline.prototype._rebuild = function () {
  60066. this._firstUpdate = true;
  60067. _super.prototype._rebuild.call(this);
  60068. };
  60069. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60070. var _this = this;
  60071. var numSamples = 16;
  60072. var sampleSphere = [
  60073. 0.5381, 0.1856, -0.4319,
  60074. 0.1379, 0.2486, 0.4430,
  60075. 0.3371, 0.5679, -0.0057,
  60076. -0.6999, -0.0451, -0.0019,
  60077. 0.0689, -0.1598, -0.8547,
  60078. 0.0560, 0.0069, -0.1843,
  60079. -0.0146, 0.1402, 0.0762,
  60080. 0.0100, -0.1924, -0.0344,
  60081. -0.3577, -0.5301, -0.4358,
  60082. -0.3169, 0.1063, 0.0158,
  60083. 0.0103, -0.5869, 0.0046,
  60084. -0.0897, -0.4940, 0.3287,
  60085. 0.7119, -0.0154, -0.0918,
  60086. -0.0533, 0.0596, -0.5411,
  60087. 0.0352, -0.0631, 0.5460,
  60088. -0.4776, 0.2847, -0.0271
  60089. ];
  60090. var samplesFactor = 1.0 / numSamples;
  60091. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60092. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60093. "area", "fallOff", "base", "range", "viewport"
  60094. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60095. this._ssaoPostProcess.onApply = function (effect) {
  60096. if (_this._firstUpdate) {
  60097. effect.setArray3("sampleSphere", sampleSphere);
  60098. effect.setFloat("samplesFactor", samplesFactor);
  60099. effect.setFloat("randTextureTiles", 4.0);
  60100. }
  60101. effect.setFloat("totalStrength", _this.totalStrength);
  60102. effect.setFloat("radius", _this.radius);
  60103. effect.setFloat("area", _this.area);
  60104. effect.setFloat("fallOff", _this.fallOff);
  60105. effect.setFloat("base", _this.base);
  60106. effect.setTexture("textureSampler", _this._depthTexture);
  60107. effect.setTexture("randomSampler", _this._randomTexture);
  60108. };
  60109. };
  60110. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60111. var _this = this;
  60112. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60113. this._ssaoCombinePostProcess.onApply = function (effect) {
  60114. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60115. };
  60116. };
  60117. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60118. var size = 512;
  60119. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60120. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60121. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60122. var context = this._randomTexture.getContext();
  60123. var rand = function (min, max) {
  60124. return Math.random() * (max - min) + min;
  60125. };
  60126. var randVector = BABYLON.Vector3.Zero();
  60127. for (var x = 0; x < size; x++) {
  60128. for (var y = 0; y < size; y++) {
  60129. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60130. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60131. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60132. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60133. context.fillRect(x, y, 1, 1);
  60134. }
  60135. }
  60136. this._randomTexture.update(false);
  60137. };
  60138. __decorate([
  60139. BABYLON.serialize()
  60140. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60141. __decorate([
  60142. BABYLON.serialize()
  60143. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60144. __decorate([
  60145. BABYLON.serialize()
  60146. ], SSAORenderingPipeline.prototype, "area", void 0);
  60147. __decorate([
  60148. BABYLON.serialize()
  60149. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60150. __decorate([
  60151. BABYLON.serialize()
  60152. ], SSAORenderingPipeline.prototype, "base", void 0);
  60153. return SSAORenderingPipeline;
  60154. }(BABYLON.PostProcessRenderPipeline));
  60155. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60156. })(BABYLON || (BABYLON = {}));
  60157. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60158. var BABYLON;
  60159. (function (BABYLON) {
  60160. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60161. __extends(SSAO2RenderingPipeline, _super);
  60162. /**
  60163. * @constructor
  60164. * @param {string} name - The rendering pipeline name
  60165. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60166. * @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 }
  60167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60168. */
  60169. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60170. var _this = _super.call(this, scene.getEngine(), name) || this;
  60171. // Members
  60172. /**
  60173. * The PassPostProcess id in the pipeline that contains the original scene color
  60174. * @type {string}
  60175. */
  60176. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60177. /**
  60178. * The SSAO PostProcess id in the pipeline
  60179. * @type {string}
  60180. */
  60181. _this.SSAORenderEffect = "SSAORenderEffect";
  60182. /**
  60183. * The horizontal blur PostProcess id in the pipeline
  60184. * @type {string}
  60185. */
  60186. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60187. /**
  60188. * The vertical blur PostProcess id in the pipeline
  60189. * @type {string}
  60190. */
  60191. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60192. /**
  60193. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60194. * @type {string}
  60195. */
  60196. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60197. /**
  60198. * The output strength of the SSAO post-process. Default value is 1.0.
  60199. * @type {number}
  60200. */
  60201. _this.totalStrength = 1.0;
  60202. /**
  60203. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60204. * @type {number}
  60205. */
  60206. _this.maxZ = 100.0;
  60207. /**
  60208. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60209. * @type {number}
  60210. */
  60211. _this.minZAspect = 0.2;
  60212. /**
  60213. * Number of samples used for the SSAO calculations. Default value is 8
  60214. * @type {number}
  60215. */
  60216. _this._samples = 8;
  60217. /**
  60218. * Are we using bilateral blur ?
  60219. * @type {boolean}
  60220. */
  60221. _this._expensiveBlur = true;
  60222. /**
  60223. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60224. * @type {number}
  60225. */
  60226. _this.radius = 2.0;
  60227. /**
  60228. * The base color of the SSAO post-process
  60229. * The final result is "base + ssao" between [0, 1]
  60230. * @type {number}
  60231. */
  60232. _this.base = 0.1;
  60233. _this._firstUpdate = true;
  60234. _this._scene = scene;
  60235. if (!_this.isSupported) {
  60236. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60237. return _this;
  60238. }
  60239. var ssaoRatio = ratio.ssaoRatio || ratio;
  60240. var blurRatio = ratio.blurRatio || ratio;
  60241. // Set up assets
  60242. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60243. _this._createRandomTexture();
  60244. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60245. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60246. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60247. _this._createSSAOPostProcess(1.0);
  60248. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60249. _this._createSSAOCombinePostProcess(blurRatio);
  60250. // Set up pipeline
  60251. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60255. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60256. // Finish
  60257. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60258. if (cameras)
  60259. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60260. return _this;
  60261. }
  60262. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60263. get: function () {
  60264. return this._samples;
  60265. },
  60266. set: function (n) {
  60267. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60268. this._samples = n;
  60269. this._sampleSphere = this._generateHemisphere();
  60270. this._firstUpdate = true;
  60271. },
  60272. enumerable: true,
  60273. configurable: true
  60274. });
  60275. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60276. get: function () {
  60277. return this._expensiveBlur;
  60278. },
  60279. set: function (b) {
  60280. 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"]);
  60281. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60282. this._expensiveBlur = b;
  60283. this._firstUpdate = true;
  60284. },
  60285. enumerable: true,
  60286. configurable: true
  60287. });
  60288. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60289. /**
  60290. * Support test.
  60291. * @type {boolean}
  60292. */
  60293. get: function () {
  60294. var engine = BABYLON.Engine.LastCreatedEngine;
  60295. if (!engine) {
  60296. return false;
  60297. }
  60298. return engine.getCaps().drawBuffersExtension;
  60299. },
  60300. enumerable: true,
  60301. configurable: true
  60302. });
  60303. // Public Methods
  60304. /**
  60305. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60306. */
  60307. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60308. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60309. for (var i = 0; i < this._scene.cameras.length; i++) {
  60310. var camera = this._scene.cameras[i];
  60311. this._originalColorPostProcess.dispose(camera);
  60312. this._ssaoPostProcess.dispose(camera);
  60313. this._blurHPostProcess.dispose(camera);
  60314. this._blurVPostProcess.dispose(camera);
  60315. this._ssaoCombinePostProcess.dispose(camera);
  60316. }
  60317. this._randomTexture.dispose();
  60318. if (disableGeometryBufferRenderer)
  60319. this._scene.disableGeometryBufferRenderer();
  60320. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60321. _super.prototype.dispose.call(this);
  60322. };
  60323. // Private Methods
  60324. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60325. var _this = this;
  60326. this._samplerOffsets = [];
  60327. var expensive = this.expensiveBlur;
  60328. for (var i = -8; i < 8; i++) {
  60329. this._samplerOffsets.push(i * 2 + 0.5);
  60330. }
  60331. 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");
  60332. this._blurHPostProcess.onApply = function (effect) {
  60333. if (!_this._scene.activeCamera) {
  60334. return;
  60335. }
  60336. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60337. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60338. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60339. effect.setFloat("radius", _this.radius);
  60340. effect.setTexture("depthSampler", _this._depthTexture);
  60341. if (_this._firstUpdate) {
  60342. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60343. }
  60344. };
  60345. 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");
  60346. this._blurVPostProcess.onApply = function (effect) {
  60347. if (!_this._scene.activeCamera) {
  60348. return;
  60349. }
  60350. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60351. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60352. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60353. effect.setFloat("radius", _this.radius);
  60354. effect.setTexture("depthSampler", _this._depthTexture);
  60355. if (_this._firstUpdate) {
  60356. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60357. _this._firstUpdate = false;
  60358. }
  60359. };
  60360. };
  60361. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60362. this._firstUpdate = true;
  60363. _super.prototype._rebuild.call(this);
  60364. };
  60365. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60366. var numSamples = this.samples;
  60367. var result = [];
  60368. var vector, scale;
  60369. var rand = function (min, max) {
  60370. return Math.random() * (max - min) + min;
  60371. };
  60372. var i = 0;
  60373. while (i < numSamples) {
  60374. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60375. vector.normalize();
  60376. scale = i / numSamples;
  60377. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60378. vector.scaleInPlace(scale);
  60379. result.push(vector.x, vector.y, vector.z);
  60380. i++;
  60381. }
  60382. return result;
  60383. };
  60384. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60385. var _this = this;
  60386. var numSamples = this.samples;
  60387. this._sampleSphere = this._generateHemisphere();
  60388. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60389. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60390. "base", "range", "projection", "near", "far", "texelSize",
  60391. "xViewport", "yViewport", "maxZ", "minZAspect"
  60392. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60393. this._ssaoPostProcess.onApply = function (effect) {
  60394. if (_this._firstUpdate) {
  60395. effect.setArray3("sampleSphere", _this._sampleSphere);
  60396. effect.setFloat("randTextureTiles", 4.0);
  60397. }
  60398. if (!_this._scene.activeCamera) {
  60399. return;
  60400. }
  60401. effect.setFloat("samplesFactor", 1 / _this.samples);
  60402. effect.setFloat("totalStrength", _this.totalStrength);
  60403. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60404. effect.setFloat("radius", _this.radius);
  60405. effect.setFloat("maxZ", _this.maxZ);
  60406. effect.setFloat("minZAspect", _this.minZAspect);
  60407. effect.setFloat("base", _this.base);
  60408. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60409. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60410. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60411. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60412. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60413. effect.setTexture("textureSampler", _this._depthTexture);
  60414. effect.setTexture("normalSampler", _this._normalTexture);
  60415. effect.setTexture("randomSampler", _this._randomTexture);
  60416. };
  60417. };
  60418. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60419. var _this = this;
  60420. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60421. this._ssaoCombinePostProcess.onApply = function (effect) {
  60422. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60423. };
  60424. };
  60425. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60426. var size = 512;
  60427. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60428. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60429. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60430. var context = this._randomTexture.getContext();
  60431. var rand = function (min, max) {
  60432. return Math.random() * (max - min) + min;
  60433. };
  60434. var randVector = BABYLON.Vector3.Zero();
  60435. for (var x = 0; x < size; x++) {
  60436. for (var y = 0; y < size; y++) {
  60437. randVector.x = rand(0.0, 1.0);
  60438. randVector.y = rand(0.0, 1.0);
  60439. randVector.z = 0.0;
  60440. randVector.normalize();
  60441. randVector.scaleInPlace(255);
  60442. randVector.x = Math.floor(randVector.x);
  60443. randVector.y = Math.floor(randVector.y);
  60444. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60445. context.fillRect(x, y, 1, 1);
  60446. }
  60447. }
  60448. this._randomTexture.update(false);
  60449. };
  60450. __decorate([
  60451. BABYLON.serialize()
  60452. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60453. __decorate([
  60454. BABYLON.serialize()
  60455. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60456. __decorate([
  60457. BABYLON.serialize()
  60458. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60459. __decorate([
  60460. BABYLON.serialize("samples")
  60461. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60462. __decorate([
  60463. BABYLON.serialize("expensiveBlur")
  60464. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60465. __decorate([
  60466. BABYLON.serialize()
  60467. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60468. __decorate([
  60469. BABYLON.serialize()
  60470. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60471. return SSAO2RenderingPipeline;
  60472. }(BABYLON.PostProcessRenderPipeline));
  60473. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60474. })(BABYLON || (BABYLON = {}));
  60475. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60476. // BABYLON.JS Chromatic Aberration GLSL Shader
  60477. // Author: Olivier Guyot
  60478. // Separates very slightly R, G and B colors on the edges of the screen
  60479. // Inspired by Francois Tarlier & Martins Upitis
  60480. var BABYLON;
  60481. (function (BABYLON) {
  60482. var LensRenderingPipeline = /** @class */ (function (_super) {
  60483. __extends(LensRenderingPipeline, _super);
  60484. /**
  60485. * @constructor
  60486. *
  60487. * Effect parameters are as follow:
  60488. * {
  60489. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60490. * edge_blur: number; // from 0 to x (1 for realism)
  60491. * distortion: number; // from 0 to x (1 for realism)
  60492. * grain_amount: number; // from 0 to 1
  60493. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60494. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60495. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60496. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60497. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60498. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60499. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60500. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60501. * }
  60502. * Note: if an effect parameter is unset, effect is disabled
  60503. *
  60504. * @param {string} name - The rendering pipeline name
  60505. * @param {object} parameters - An object containing all parameters (see above)
  60506. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60507. * @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)
  60508. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60509. */
  60510. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60511. if (ratio === void 0) { ratio = 1.0; }
  60512. var _this = _super.call(this, scene.getEngine(), name) || this;
  60513. // Lens effects can be of the following:
  60514. // - chromatic aberration (slight shift of RGB colors)
  60515. // - blur on the edge of the lens
  60516. // - lens distortion
  60517. // - depth-of-field blur & highlights enhancing
  60518. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60519. // - grain effect (noise or custom texture)
  60520. // Two additional texture samplers are needed:
  60521. // - depth map (for depth-of-field)
  60522. // - grain texture
  60523. /**
  60524. * The chromatic aberration PostProcess id in the pipeline
  60525. * @type {string}
  60526. */
  60527. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60528. /**
  60529. * The highlights enhancing PostProcess id in the pipeline
  60530. * @type {string}
  60531. */
  60532. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60533. /**
  60534. * The depth-of-field PostProcess id in the pipeline
  60535. * @type {string}
  60536. */
  60537. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60538. _this._scene = scene;
  60539. // Fetch texture samplers
  60540. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60541. if (parameters.grain_texture) {
  60542. _this._grainTexture = parameters.grain_texture;
  60543. }
  60544. else {
  60545. _this._createGrainTexture();
  60546. }
  60547. // save parameters
  60548. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60549. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60550. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60551. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60552. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60553. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60554. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60555. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60556. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60557. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60558. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60559. // Create effects
  60560. _this._createChromaticAberrationPostProcess(ratio);
  60561. _this._createHighlightsPostProcess(ratio);
  60562. _this._createDepthOfFieldPostProcess(ratio / 4);
  60563. // Set up pipeline
  60564. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60565. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60566. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60567. if (_this._highlightsGain === -1) {
  60568. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60569. }
  60570. // Finish
  60571. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60572. if (cameras) {
  60573. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60574. }
  60575. return _this;
  60576. }
  60577. // public methods (self explanatory)
  60578. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60579. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60580. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60581. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60582. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60583. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60584. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60585. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60586. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60587. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60588. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60589. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60590. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60591. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60592. };
  60593. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60594. this._highlightsPostProcess.updateEffect();
  60595. };
  60596. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60597. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60598. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60599. this._highlightsGain = amount;
  60600. };
  60601. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60602. if (this._highlightsGain === -1) {
  60603. this._highlightsGain = 1.0;
  60604. }
  60605. this._highlightsThreshold = amount;
  60606. };
  60607. LensRenderingPipeline.prototype.disableHighlights = function () {
  60608. this._highlightsGain = -1;
  60609. };
  60610. /**
  60611. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60612. */
  60613. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60614. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60615. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60616. this._chromaticAberrationPostProcess = null;
  60617. this._highlightsPostProcess = null;
  60618. this._depthOfFieldPostProcess = null;
  60619. this._grainTexture.dispose();
  60620. if (disableDepthRender)
  60621. this._scene.disableDepthRenderer();
  60622. };
  60623. // colors shifting and distortion
  60624. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60625. var _this = this;
  60626. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60627. [], // samplers
  60628. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60629. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60630. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60631. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60632. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60633. };
  60634. };
  60635. // highlights enhancing
  60636. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60637. var _this = this;
  60638. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60639. [], // samplers
  60640. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60641. this._highlightsPostProcess.onApply = function (effect) {
  60642. effect.setFloat('gain', _this._highlightsGain);
  60643. effect.setFloat('threshold', _this._highlightsThreshold);
  60644. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60645. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60646. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60647. };
  60648. };
  60649. // colors shifting and distortion
  60650. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60651. var _this = this;
  60652. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60653. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60654. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60655. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60656. this._depthOfFieldPostProcess.onApply = function (effect) {
  60657. effect.setTexture("depthSampler", _this._depthTexture);
  60658. effect.setTexture("grainSampler", _this._grainTexture);
  60659. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60660. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60661. effect.setFloat('grain_amount', _this._grainAmount);
  60662. effect.setBool('blur_noise', _this._blurNoise);
  60663. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60664. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60665. effect.setFloat('distortion', _this._distortion);
  60666. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60667. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60668. effect.setFloat('aperture', _this._dofAperture);
  60669. effect.setFloat('darken', _this._dofDarken);
  60670. effect.setFloat('edge_blur', _this._edgeBlur);
  60671. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60672. if (_this._scene.activeCamera) {
  60673. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60674. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60675. }
  60676. };
  60677. };
  60678. // creates a black and white random noise texture, 512x512
  60679. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60680. var size = 512;
  60681. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60682. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60683. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60684. var context = this._grainTexture.getContext();
  60685. var rand = function (min, max) {
  60686. return Math.random() * (max - min) + min;
  60687. };
  60688. var value;
  60689. for (var x = 0; x < size; x++) {
  60690. for (var y = 0; y < size; y++) {
  60691. value = Math.floor(rand(0.42, 0.58) * 255);
  60692. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60693. context.fillRect(x, y, 1, 1);
  60694. }
  60695. }
  60696. this._grainTexture.update(false);
  60697. };
  60698. return LensRenderingPipeline;
  60699. }(BABYLON.PostProcessRenderPipeline));
  60700. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60701. })(BABYLON || (BABYLON = {}));
  60702. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60703. var BABYLON;
  60704. (function (BABYLON) {
  60705. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60706. __extends(StandardRenderingPipeline, _super);
  60707. /**
  60708. * @constructor
  60709. * @param {string} name - The rendering pipeline name
  60710. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60711. * @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)
  60712. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60713. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60714. */
  60715. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60716. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60717. var _this = _super.call(this, scene.getEngine(), name) || this;
  60718. _this.downSampleX4PostProcess = null;
  60719. _this.brightPassPostProcess = null;
  60720. _this.blurHPostProcesses = [];
  60721. _this.blurVPostProcesses = [];
  60722. _this.textureAdderPostProcess = null;
  60723. _this.volumetricLightPostProcess = null;
  60724. _this.volumetricLightSmoothXPostProcess = null;
  60725. _this.volumetricLightSmoothYPostProcess = null;
  60726. _this.volumetricLightMergePostProces = null;
  60727. _this.volumetricLightFinalPostProcess = null;
  60728. _this.luminancePostProcess = null;
  60729. _this.luminanceDownSamplePostProcesses = [];
  60730. _this.hdrPostProcess = null;
  60731. _this.textureAdderFinalPostProcess = null;
  60732. _this.lensFlareFinalPostProcess = null;
  60733. _this.hdrFinalPostProcess = null;
  60734. _this.lensFlarePostProcess = null;
  60735. _this.lensFlareComposePostProcess = null;
  60736. _this.motionBlurPostProcess = null;
  60737. _this.depthOfFieldPostProcess = null;
  60738. // Values
  60739. _this.brightThreshold = 1.0;
  60740. _this.blurWidth = 512.0;
  60741. _this.horizontalBlur = false;
  60742. _this.exposure = 1.0;
  60743. _this.lensTexture = null;
  60744. _this.volumetricLightCoefficient = 0.2;
  60745. _this.volumetricLightPower = 4.0;
  60746. _this.volumetricLightBlurScale = 64.0;
  60747. _this.sourceLight = null;
  60748. _this.hdrMinimumLuminance = 1.0;
  60749. _this.hdrDecreaseRate = 0.5;
  60750. _this.hdrIncreaseRate = 0.5;
  60751. _this.lensColorTexture = null;
  60752. _this.lensFlareStrength = 20.0;
  60753. _this.lensFlareGhostDispersal = 1.4;
  60754. _this.lensFlareHaloWidth = 0.7;
  60755. _this.lensFlareDistortionStrength = 16.0;
  60756. _this.lensStarTexture = null;
  60757. _this.lensFlareDirtTexture = null;
  60758. _this.depthOfFieldDistance = 10.0;
  60759. _this.depthOfFieldBlurWidth = 64.0;
  60760. _this.motionStrength = 1.0;
  60761. // IAnimatable
  60762. _this.animations = [];
  60763. _this._currentDepthOfFieldSource = null;
  60764. _this._hdrCurrentLuminance = 1.0;
  60765. // Getters and setters
  60766. _this._bloomEnabled = true;
  60767. _this._depthOfFieldEnabled = false;
  60768. _this._vlsEnabled = false;
  60769. _this._lensFlareEnabled = false;
  60770. _this._hdrEnabled = false;
  60771. _this._motionBlurEnabled = false;
  60772. _this._motionBlurSamples = 64.0;
  60773. _this._volumetricLightStepsCount = 50.0;
  60774. _this._cameras = cameras || [];
  60775. // Initialize
  60776. _this._scene = scene;
  60777. _this._basePostProcess = originalPostProcess;
  60778. _this._ratio = ratio;
  60779. // Misc
  60780. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60781. // Finish
  60782. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60783. _this._buildPipeline();
  60784. return _this;
  60785. }
  60786. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60787. get: function () {
  60788. return this._bloomEnabled;
  60789. },
  60790. set: function (enabled) {
  60791. if (this._bloomEnabled === enabled) {
  60792. return;
  60793. }
  60794. this._bloomEnabled = enabled;
  60795. this._buildPipeline();
  60796. },
  60797. enumerable: true,
  60798. configurable: true
  60799. });
  60800. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60801. get: function () {
  60802. return this._depthOfFieldEnabled;
  60803. },
  60804. set: function (enabled) {
  60805. if (this._depthOfFieldEnabled === enabled) {
  60806. return;
  60807. }
  60808. this._depthOfFieldEnabled = enabled;
  60809. this._buildPipeline();
  60810. },
  60811. enumerable: true,
  60812. configurable: true
  60813. });
  60814. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60815. get: function () {
  60816. return this._lensFlareEnabled;
  60817. },
  60818. set: function (enabled) {
  60819. if (this._lensFlareEnabled === enabled) {
  60820. return;
  60821. }
  60822. this._lensFlareEnabled = enabled;
  60823. this._buildPipeline();
  60824. },
  60825. enumerable: true,
  60826. configurable: true
  60827. });
  60828. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60829. get: function () {
  60830. return this._hdrEnabled;
  60831. },
  60832. set: function (enabled) {
  60833. if (this._hdrEnabled === enabled) {
  60834. return;
  60835. }
  60836. this._hdrEnabled = enabled;
  60837. this._buildPipeline();
  60838. },
  60839. enumerable: true,
  60840. configurable: true
  60841. });
  60842. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60843. get: function () {
  60844. return this._vlsEnabled;
  60845. },
  60846. set: function (enabled) {
  60847. if (this._vlsEnabled === enabled) {
  60848. return;
  60849. }
  60850. if (enabled) {
  60851. var geometry = this._scene.enableGeometryBufferRenderer();
  60852. if (!geometry) {
  60853. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60854. return;
  60855. }
  60856. }
  60857. this._vlsEnabled = enabled;
  60858. this._buildPipeline();
  60859. },
  60860. enumerable: true,
  60861. configurable: true
  60862. });
  60863. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60864. get: function () {
  60865. return this._motionBlurEnabled;
  60866. },
  60867. set: function (enabled) {
  60868. if (this._motionBlurEnabled === enabled) {
  60869. return;
  60870. }
  60871. this._motionBlurEnabled = enabled;
  60872. this._buildPipeline();
  60873. },
  60874. enumerable: true,
  60875. configurable: true
  60876. });
  60877. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60878. get: function () {
  60879. return this._volumetricLightStepsCount;
  60880. },
  60881. set: function (count) {
  60882. if (this.volumetricLightPostProcess) {
  60883. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60884. }
  60885. this._volumetricLightStepsCount = count;
  60886. },
  60887. enumerable: true,
  60888. configurable: true
  60889. });
  60890. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60891. get: function () {
  60892. return this._motionBlurSamples;
  60893. },
  60894. set: function (samples) {
  60895. if (this.motionBlurPostProcess) {
  60896. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60897. }
  60898. this._motionBlurSamples = samples;
  60899. },
  60900. enumerable: true,
  60901. configurable: true
  60902. });
  60903. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60904. var _this = this;
  60905. var ratio = this._ratio;
  60906. var scene = this._scene;
  60907. this._disposePostProcesses();
  60908. this._reset();
  60909. // Create pass post-process
  60910. if (!this._basePostProcess) {
  60911. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60912. this.originalPostProcess.onApply = function (effect) {
  60913. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60914. };
  60915. }
  60916. else {
  60917. this.originalPostProcess = this._basePostProcess;
  60918. }
  60919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60920. this._currentDepthOfFieldSource = this.originalPostProcess;
  60921. if (this._vlsEnabled) {
  60922. // Create volumetric light
  60923. this._createVolumetricLightPostProcess(scene, ratio);
  60924. // Create volumetric light final post-process
  60925. 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);
  60926. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60927. }
  60928. if (this._bloomEnabled) {
  60929. // Create down sample X4 post-process
  60930. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60931. // Create bright pass post-process
  60932. this._createBrightPassPostProcess(scene, ratio / 2);
  60933. // Create gaussian blur post-processes (down sampling blurs)
  60934. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60935. // Create texture adder post-process
  60936. this._createTextureAdderPostProcess(scene, ratio);
  60937. // Create depth-of-field source post-process
  60938. 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);
  60939. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60940. }
  60941. if (this._lensFlareEnabled) {
  60942. // Create lens flare post-process
  60943. this._createLensFlarePostProcess(scene, ratio);
  60944. // Create depth-of-field source post-process post lens-flare and disable it now
  60945. 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);
  60946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60947. }
  60948. if (this._hdrEnabled) {
  60949. // Create luminance
  60950. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60951. // Create HDR
  60952. this._createHdrPostProcess(scene, ratio);
  60953. // Create depth-of-field source post-process post hdr and disable it now
  60954. 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);
  60955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60956. }
  60957. if (this._depthOfFieldEnabled) {
  60958. // Create gaussian blur used by depth-of-field
  60959. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60960. // Create depth-of-field post-process
  60961. this._createDepthOfFieldPostProcess(scene, ratio);
  60962. }
  60963. if (this._motionBlurEnabled) {
  60964. // Create motion blur post-process
  60965. this._createMotionBlurPostProcess(scene, ratio);
  60966. }
  60967. if (this._cameras !== null) {
  60968. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60969. }
  60970. };
  60971. // Down Sample X4 Post-Processs
  60972. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60973. var _this = this;
  60974. var downSampleX4Offsets = new Array(32);
  60975. 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);
  60976. this.downSampleX4PostProcess.onApply = function (effect) {
  60977. var id = 0;
  60978. var width = _this.downSampleX4PostProcess.width;
  60979. var height = _this.downSampleX4PostProcess.height;
  60980. for (var i = -2; i < 2; i++) {
  60981. for (var j = -2; j < 2; j++) {
  60982. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60983. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60984. id += 2;
  60985. }
  60986. }
  60987. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60988. };
  60989. // Add to pipeline
  60990. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60991. };
  60992. // Brightpass Post-Process
  60993. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60994. var _this = this;
  60995. var brightOffsets = new Array(8);
  60996. 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);
  60997. this.brightPassPostProcess.onApply = function (effect) {
  60998. var sU = (1.0 / _this.brightPassPostProcess.width);
  60999. var sV = (1.0 / _this.brightPassPostProcess.height);
  61000. brightOffsets[0] = -0.5 * sU;
  61001. brightOffsets[1] = 0.5 * sV;
  61002. brightOffsets[2] = 0.5 * sU;
  61003. brightOffsets[3] = 0.5 * sV;
  61004. brightOffsets[4] = -0.5 * sU;
  61005. brightOffsets[5] = -0.5 * sV;
  61006. brightOffsets[6] = 0.5 * sU;
  61007. brightOffsets[7] = -0.5 * sV;
  61008. effect.setArray2("dsOffsets", brightOffsets);
  61009. effect.setFloat("brightThreshold", _this.brightThreshold);
  61010. };
  61011. // Add to pipeline
  61012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61013. };
  61014. // Create blur H&V post-processes
  61015. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61016. var _this = this;
  61017. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61018. var engine = scene.getEngine();
  61019. 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);
  61020. 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);
  61021. blurX.onActivateObservable.add(function () {
  61022. var dw = blurX.width / engine.getRenderWidth();
  61023. blurX.kernel = _this[blurWidthKey] * dw;
  61024. });
  61025. blurY.onActivateObservable.add(function () {
  61026. var dw = blurY.height / engine.getRenderHeight();
  61027. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61028. });
  61029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61031. this.blurHPostProcesses.push(blurX);
  61032. this.blurVPostProcesses.push(blurY);
  61033. };
  61034. // Create texture adder post-process
  61035. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61036. var _this = this;
  61037. 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);
  61038. this.textureAdderPostProcess.onApply = function (effect) {
  61039. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61040. effect.setTexture("lensSampler", _this.lensTexture);
  61041. effect.setFloat("exposure", _this.exposure);
  61042. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61043. };
  61044. // Add to pipeline
  61045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61046. };
  61047. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61048. var _this = this;
  61049. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61050. geometryRenderer.enablePosition = true;
  61051. var geometry = geometryRenderer.getGBuffer();
  61052. // Base post-process
  61053. 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));
  61054. var depthValues = BABYLON.Vector2.Zero();
  61055. this.volumetricLightPostProcess.onApply = function (effect) {
  61056. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61057. var generator = _this.sourceLight.getShadowGenerator();
  61058. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61059. effect.setTexture("positionSampler", geometry.textures[2]);
  61060. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61061. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61062. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61063. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61064. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61065. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61066. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61067. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61068. effect.setVector2("depthValues", depthValues);
  61069. }
  61070. };
  61071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61072. // Smooth
  61073. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61074. // Merge
  61075. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61076. this.volumetricLightMergePostProces.onApply = function (effect) {
  61077. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61078. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61079. };
  61080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61081. };
  61082. // Create luminance
  61083. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61084. var _this = this;
  61085. // Create luminance
  61086. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61087. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61088. var offsets = [];
  61089. this.luminancePostProcess.onApply = function (effect) {
  61090. var sU = (1.0 / _this.luminancePostProcess.width);
  61091. var sV = (1.0 / _this.luminancePostProcess.height);
  61092. offsets[0] = -0.5 * sU;
  61093. offsets[1] = 0.5 * sV;
  61094. offsets[2] = 0.5 * sU;
  61095. offsets[3] = 0.5 * sV;
  61096. offsets[4] = -0.5 * sU;
  61097. offsets[5] = -0.5 * sV;
  61098. offsets[6] = 0.5 * sU;
  61099. offsets[7] = -0.5 * sV;
  61100. effect.setArray2("lumOffsets", offsets);
  61101. };
  61102. // Add to pipeline
  61103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61104. // Create down sample luminance
  61105. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61106. var size = Math.pow(3, i);
  61107. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61108. if (i === 0) {
  61109. defines += "#define FINAL_DOWN_SAMPLER";
  61110. }
  61111. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61112. this.luminanceDownSamplePostProcesses.push(postProcess);
  61113. }
  61114. // Create callbacks and add effects
  61115. var lastLuminance = this.luminancePostProcess;
  61116. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61117. var downSampleOffsets = new Array(18);
  61118. pp.onApply = function (effect) {
  61119. if (!lastLuminance) {
  61120. return;
  61121. }
  61122. var id = 0;
  61123. for (var x = -1; x < 2; x++) {
  61124. for (var y = -1; y < 2; y++) {
  61125. downSampleOffsets[id] = x / lastLuminance.width;
  61126. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61127. id += 2;
  61128. }
  61129. }
  61130. effect.setArray2("dsOffsets", downSampleOffsets);
  61131. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61132. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61133. lastLuminance = _this.luminancePostProcess;
  61134. }
  61135. else {
  61136. lastLuminance = pp;
  61137. }
  61138. };
  61139. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61140. pp.onAfterRender = function (effect) {
  61141. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61142. 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);
  61143. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61144. };
  61145. }
  61146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61147. });
  61148. };
  61149. // Create HDR post-process
  61150. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61151. var _this = this;
  61152. 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);
  61153. var outputLiminance = 1;
  61154. var time = 0;
  61155. var lastTime = 0;
  61156. this.hdrPostProcess.onApply = function (effect) {
  61157. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61158. time += scene.getEngine().getDeltaTime();
  61159. if (outputLiminance < 0) {
  61160. outputLiminance = _this._hdrCurrentLuminance;
  61161. }
  61162. else {
  61163. var dt = (lastTime - time) / 1000.0;
  61164. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61165. outputLiminance += _this.hdrDecreaseRate * dt;
  61166. }
  61167. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61168. outputLiminance -= _this.hdrIncreaseRate * dt;
  61169. }
  61170. else {
  61171. outputLiminance = _this._hdrCurrentLuminance;
  61172. }
  61173. }
  61174. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61175. effect.setFloat("averageLuminance", outputLiminance);
  61176. lastTime = time;
  61177. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61178. };
  61179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61180. };
  61181. // Create lens flare post-process
  61182. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61183. var _this = this;
  61184. 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);
  61185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61186. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61187. 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);
  61188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61189. var resolution = new BABYLON.Vector2(0, 0);
  61190. // Lens flare
  61191. this.lensFlarePostProcess.onApply = function (effect) {
  61192. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61193. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61194. effect.setFloat("strength", _this.lensFlareStrength);
  61195. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61196. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61197. // Shift
  61198. resolution.x = _this.lensFlarePostProcess.width;
  61199. resolution.y = _this.lensFlarePostProcess.height;
  61200. effect.setVector2("resolution", resolution);
  61201. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61202. };
  61203. // Compose
  61204. 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);
  61205. 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);
  61206. this.lensFlareComposePostProcess.onApply = function (effect) {
  61207. if (!_this._scene.activeCamera) {
  61208. return;
  61209. }
  61210. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61211. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61212. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61213. // Lens start rotation matrix
  61214. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61215. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61216. 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));
  61217. camRot *= 4.0;
  61218. 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);
  61219. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61220. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61221. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61222. };
  61223. };
  61224. // Create depth-of-field post-process
  61225. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61226. var _this = this;
  61227. 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);
  61228. this.depthOfFieldPostProcess.onApply = function (effect) {
  61229. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61230. effect.setTexture("depthSampler", _this._getDepthTexture());
  61231. effect.setFloat("distance", _this.depthOfFieldDistance);
  61232. };
  61233. // Add to pipeline
  61234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61235. };
  61236. // Create motion blur post-process
  61237. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61238. var _this = this;
  61239. 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);
  61240. var motionScale = 0;
  61241. var prevViewProjection = BABYLON.Matrix.Identity();
  61242. var invViewProjection = BABYLON.Matrix.Identity();
  61243. var viewProjection = BABYLON.Matrix.Identity();
  61244. var screenSize = BABYLON.Vector2.Zero();
  61245. this.motionBlurPostProcess.onApply = function (effect) {
  61246. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61247. viewProjection.invertToRef(invViewProjection);
  61248. effect.setMatrix("inverseViewProjection", invViewProjection);
  61249. effect.setMatrix("prevViewProjection", prevViewProjection);
  61250. prevViewProjection = viewProjection;
  61251. screenSize.x = _this.motionBlurPostProcess.width;
  61252. screenSize.y = _this.motionBlurPostProcess.height;
  61253. effect.setVector2("screenSize", screenSize);
  61254. motionScale = scene.getEngine().getFps() / 60.0;
  61255. effect.setFloat("motionScale", motionScale);
  61256. effect.setFloat("motionStrength", _this.motionStrength);
  61257. effect.setTexture("depthSampler", _this._getDepthTexture());
  61258. };
  61259. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61260. };
  61261. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61262. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61263. var renderer = this._scene.enableGeometryBufferRenderer();
  61264. return renderer.getGBuffer().textures[0];
  61265. }
  61266. return this._scene.enableDepthRenderer().getDepthMap();
  61267. };
  61268. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61269. for (var i = 0; i < this._cameras.length; i++) {
  61270. var camera = this._cameras[i];
  61271. if (this.originalPostProcess) {
  61272. this.originalPostProcess.dispose(camera);
  61273. }
  61274. if (this.downSampleX4PostProcess) {
  61275. this.downSampleX4PostProcess.dispose(camera);
  61276. }
  61277. if (this.brightPassPostProcess) {
  61278. this.brightPassPostProcess.dispose(camera);
  61279. }
  61280. if (this.textureAdderPostProcess) {
  61281. this.textureAdderPostProcess.dispose(camera);
  61282. }
  61283. if (this.textureAdderFinalPostProcess) {
  61284. this.textureAdderFinalPostProcess.dispose(camera);
  61285. }
  61286. if (this.volumetricLightPostProcess) {
  61287. this.volumetricLightPostProcess.dispose(camera);
  61288. }
  61289. if (this.volumetricLightSmoothXPostProcess) {
  61290. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61291. }
  61292. if (this.volumetricLightSmoothYPostProcess) {
  61293. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61294. }
  61295. if (this.volumetricLightMergePostProces) {
  61296. this.volumetricLightMergePostProces.dispose(camera);
  61297. }
  61298. if (this.volumetricLightFinalPostProcess) {
  61299. this.volumetricLightFinalPostProcess.dispose(camera);
  61300. }
  61301. if (this.lensFlarePostProcess) {
  61302. this.lensFlarePostProcess.dispose(camera);
  61303. }
  61304. if (this.lensFlareComposePostProcess) {
  61305. this.lensFlareComposePostProcess.dispose(camera);
  61306. }
  61307. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61308. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61309. }
  61310. if (this.luminancePostProcess) {
  61311. this.luminancePostProcess.dispose(camera);
  61312. }
  61313. if (this.hdrPostProcess) {
  61314. this.hdrPostProcess.dispose(camera);
  61315. }
  61316. if (this.hdrFinalPostProcess) {
  61317. this.hdrFinalPostProcess.dispose(camera);
  61318. }
  61319. if (this.depthOfFieldPostProcess) {
  61320. this.depthOfFieldPostProcess.dispose(camera);
  61321. }
  61322. if (this.motionBlurPostProcess) {
  61323. this.motionBlurPostProcess.dispose(camera);
  61324. }
  61325. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61326. this.blurHPostProcesses[j].dispose(camera);
  61327. }
  61328. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61329. this.blurVPostProcesses[j].dispose(camera);
  61330. }
  61331. }
  61332. this.originalPostProcess = null;
  61333. this.downSampleX4PostProcess = null;
  61334. this.brightPassPostProcess = null;
  61335. this.textureAdderPostProcess = null;
  61336. this.textureAdderFinalPostProcess = null;
  61337. this.volumetricLightPostProcess = null;
  61338. this.volumetricLightSmoothXPostProcess = null;
  61339. this.volumetricLightSmoothYPostProcess = null;
  61340. this.volumetricLightMergePostProces = null;
  61341. this.volumetricLightFinalPostProcess = null;
  61342. this.lensFlarePostProcess = null;
  61343. this.lensFlareComposePostProcess = null;
  61344. this.luminancePostProcess = null;
  61345. this.hdrPostProcess = null;
  61346. this.hdrFinalPostProcess = null;
  61347. this.depthOfFieldPostProcess = null;
  61348. this.motionBlurPostProcess = null;
  61349. this.luminanceDownSamplePostProcesses = [];
  61350. this.blurHPostProcesses = [];
  61351. this.blurVPostProcesses = [];
  61352. };
  61353. // Dispose
  61354. StandardRenderingPipeline.prototype.dispose = function () {
  61355. this._disposePostProcesses();
  61356. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61357. _super.prototype.dispose.call(this);
  61358. };
  61359. // Serialize rendering pipeline
  61360. StandardRenderingPipeline.prototype.serialize = function () {
  61361. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61362. serializationObject.customType = "StandardRenderingPipeline";
  61363. return serializationObject;
  61364. };
  61365. /**
  61366. * Static members
  61367. */
  61368. // Parse serialized pipeline
  61369. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61370. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61371. };
  61372. // Luminance steps
  61373. StandardRenderingPipeline.LuminanceSteps = 6;
  61374. __decorate([
  61375. BABYLON.serialize()
  61376. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61377. __decorate([
  61378. BABYLON.serialize()
  61379. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61380. __decorate([
  61381. BABYLON.serialize()
  61382. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61383. __decorate([
  61384. BABYLON.serialize()
  61385. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61386. __decorate([
  61387. BABYLON.serializeAsTexture("lensTexture")
  61388. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61389. __decorate([
  61390. BABYLON.serialize()
  61391. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61392. __decorate([
  61393. BABYLON.serialize()
  61394. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61395. __decorate([
  61396. BABYLON.serialize()
  61397. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61398. __decorate([
  61399. BABYLON.serialize()
  61400. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61401. __decorate([
  61402. BABYLON.serialize()
  61403. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61404. __decorate([
  61405. BABYLON.serialize()
  61406. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61407. __decorate([
  61408. BABYLON.serializeAsTexture("lensColorTexture")
  61409. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61410. __decorate([
  61411. BABYLON.serialize()
  61412. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61413. __decorate([
  61414. BABYLON.serialize()
  61415. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61416. __decorate([
  61417. BABYLON.serialize()
  61418. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61419. __decorate([
  61420. BABYLON.serialize()
  61421. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61422. __decorate([
  61423. BABYLON.serializeAsTexture("lensStarTexture")
  61424. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61425. __decorate([
  61426. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61427. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61428. __decorate([
  61429. BABYLON.serialize()
  61430. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61431. __decorate([
  61432. BABYLON.serialize()
  61433. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61434. __decorate([
  61435. BABYLON.serialize()
  61436. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61437. __decorate([
  61438. BABYLON.serialize()
  61439. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61440. __decorate([
  61441. BABYLON.serialize()
  61442. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61443. __decorate([
  61444. BABYLON.serialize()
  61445. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61446. __decorate([
  61447. BABYLON.serialize()
  61448. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61449. __decorate([
  61450. BABYLON.serialize()
  61451. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61452. __decorate([
  61453. BABYLON.serialize()
  61454. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61455. __decorate([
  61456. BABYLON.serialize()
  61457. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61458. __decorate([
  61459. BABYLON.serialize()
  61460. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61461. __decorate([
  61462. BABYLON.serialize()
  61463. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61464. return StandardRenderingPipeline;
  61465. }(BABYLON.PostProcessRenderPipeline));
  61466. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61467. })(BABYLON || (BABYLON = {}));
  61468. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61469. var BABYLON;
  61470. (function (BABYLON) {
  61471. var FxaaPostProcess = /** @class */ (function (_super) {
  61472. __extends(FxaaPostProcess, _super);
  61473. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61474. if (camera === void 0) { camera = null; }
  61475. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61476. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61477. _this.onApplyObservable.add(function (effect) {
  61478. var texelSize = _this.texelSize;
  61479. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61480. });
  61481. return _this;
  61482. }
  61483. return FxaaPostProcess;
  61484. }(BABYLON.PostProcess));
  61485. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61486. })(BABYLON || (BABYLON = {}));
  61487. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61488. var BABYLON;
  61489. (function (BABYLON) {
  61490. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61491. __extends(DefaultRenderingPipeline, _super);
  61492. /**
  61493. * @constructor
  61494. * @param {string} name - The rendering pipeline name
  61495. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61496. * @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)
  61497. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61498. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61499. */
  61500. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61501. if (automaticBuild === void 0) { automaticBuild = true; }
  61502. var _this = _super.call(this, scene.getEngine(), name) || this;
  61503. _this.PassPostProcessId = "PassPostProcessEffect";
  61504. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61505. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61506. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61507. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61508. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61509. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61510. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61511. // IAnimatable
  61512. _this.animations = [];
  61513. // Values
  61514. _this._bloomEnabled = false;
  61515. _this._fxaaEnabled = false;
  61516. _this._imageProcessingEnabled = true;
  61517. _this._bloomScale = 0.6;
  61518. _this._buildAllowed = true;
  61519. /**
  61520. * Specifies the size of the bloom blur kernel, relative to the final output size
  61521. */
  61522. _this.bloomKernel = 64;
  61523. /**
  61524. * Specifies the weight of the bloom in the final rendering
  61525. */
  61526. _this._bloomWeight = 0.15;
  61527. _this._cameras = cameras || [];
  61528. _this._buildAllowed = automaticBuild;
  61529. // Initialize
  61530. _this._scene = scene;
  61531. var caps = _this._scene.getEngine().getCaps();
  61532. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61533. // Misc
  61534. if (_this._hdr) {
  61535. if (caps.textureHalfFloatRender) {
  61536. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61537. }
  61538. else if (caps.textureFloatRender) {
  61539. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61540. }
  61541. }
  61542. else {
  61543. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61544. }
  61545. // Attach
  61546. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61547. _this._buildPipeline();
  61548. return _this;
  61549. }
  61550. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61551. get: function () {
  61552. return this._bloomWeight;
  61553. },
  61554. set: function (value) {
  61555. if (this._bloomWeight === value) {
  61556. return;
  61557. }
  61558. this._bloomWeight = value;
  61559. if (this._hdr && this.copyBack) {
  61560. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61561. }
  61562. },
  61563. enumerable: true,
  61564. configurable: true
  61565. });
  61566. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61567. get: function () {
  61568. return this._bloomScale;
  61569. },
  61570. set: function (value) {
  61571. if (this._bloomScale === value) {
  61572. return;
  61573. }
  61574. this._bloomScale = value;
  61575. this._buildPipeline();
  61576. },
  61577. enumerable: true,
  61578. configurable: true
  61579. });
  61580. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61581. get: function () {
  61582. return this._bloomEnabled;
  61583. },
  61584. set: function (enabled) {
  61585. if (this._bloomEnabled === enabled) {
  61586. return;
  61587. }
  61588. this._bloomEnabled = enabled;
  61589. this._buildPipeline();
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61595. get: function () {
  61596. return this._fxaaEnabled;
  61597. },
  61598. set: function (enabled) {
  61599. if (this._fxaaEnabled === enabled) {
  61600. return;
  61601. }
  61602. this._fxaaEnabled = enabled;
  61603. this._buildPipeline();
  61604. },
  61605. enumerable: true,
  61606. configurable: true
  61607. });
  61608. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61609. get: function () {
  61610. return this._imageProcessingEnabled;
  61611. },
  61612. set: function (enabled) {
  61613. if (this._imageProcessingEnabled === enabled) {
  61614. return;
  61615. }
  61616. this._imageProcessingEnabled = enabled;
  61617. this._buildPipeline();
  61618. },
  61619. enumerable: true,
  61620. configurable: true
  61621. });
  61622. /**
  61623. * Force the compilation of the entire pipeline.
  61624. */
  61625. DefaultRenderingPipeline.prototype.prepare = function () {
  61626. var previousState = this._buildAllowed;
  61627. this._buildAllowed = true;
  61628. this._buildPipeline();
  61629. this._buildAllowed = previousState;
  61630. };
  61631. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61632. var _this = this;
  61633. if (!this._buildAllowed) {
  61634. return;
  61635. }
  61636. var engine = this._scene.getEngine();
  61637. this._disposePostProcesses();
  61638. this._reset();
  61639. if (this.bloomEnabled) {
  61640. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61641. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61642. if (!this._hdr) {
  61643. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61644. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61645. this.highlights.autoClear = false;
  61646. this.highlights.alwaysForcePOT = true;
  61647. }
  61648. 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);
  61649. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61650. this.blurX.alwaysForcePOT = true;
  61651. this.blurX.autoClear = false;
  61652. this.blurX.onActivateObservable.add(function () {
  61653. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61654. _this.blurX.kernel = _this.bloomKernel * dw;
  61655. });
  61656. 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);
  61657. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61658. this.blurY.alwaysForcePOT = true;
  61659. this.blurY.autoClear = false;
  61660. this.blurY.onActivateObservable.add(function () {
  61661. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61662. _this.blurY.kernel = _this.bloomKernel * dh;
  61663. });
  61664. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61666. this.copyBack.alwaysForcePOT = true;
  61667. if (this._hdr) {
  61668. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61669. var w = this.bloomWeight;
  61670. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61671. }
  61672. else {
  61673. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61674. }
  61675. this.copyBack.autoClear = false;
  61676. }
  61677. if (this._imageProcessingEnabled) {
  61678. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61679. if (this._hdr) {
  61680. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61681. }
  61682. else {
  61683. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61684. }
  61685. }
  61686. if (this.fxaaEnabled) {
  61687. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61688. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61689. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61690. }
  61691. else if (this._hdr && this.imageProcessing) {
  61692. this.finalMerge = this.imageProcessing;
  61693. }
  61694. else {
  61695. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61696. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61697. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61698. }
  61699. if (this.bloomEnabled) {
  61700. if (this._hdr) {
  61701. this.copyBack.shareOutputWith(this.blurX);
  61702. if (this.imageProcessing) {
  61703. this.imageProcessing.shareOutputWith(this.pass);
  61704. this.imageProcessing.autoClear = false;
  61705. }
  61706. else if (this.fxaa) {
  61707. this.fxaa.shareOutputWith(this.pass);
  61708. }
  61709. else {
  61710. this.finalMerge.shareOutputWith(this.pass);
  61711. }
  61712. }
  61713. else {
  61714. if (this.fxaa) {
  61715. this.fxaa.shareOutputWith(this.pass);
  61716. }
  61717. else {
  61718. this.finalMerge.shareOutputWith(this.pass);
  61719. }
  61720. }
  61721. }
  61722. if (this._cameras !== null) {
  61723. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61724. }
  61725. };
  61726. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61727. for (var i = 0; i < this._cameras.length; i++) {
  61728. var camera = this._cameras[i];
  61729. if (this.pass) {
  61730. this.pass.dispose(camera);
  61731. }
  61732. if (this.highlights) {
  61733. this.highlights.dispose(camera);
  61734. }
  61735. if (this.blurX) {
  61736. this.blurX.dispose(camera);
  61737. }
  61738. if (this.blurY) {
  61739. this.blurY.dispose(camera);
  61740. }
  61741. if (this.copyBack) {
  61742. this.copyBack.dispose(camera);
  61743. }
  61744. if (this.imageProcessing) {
  61745. this.imageProcessing.dispose(camera);
  61746. }
  61747. if (this.fxaa) {
  61748. this.fxaa.dispose(camera);
  61749. }
  61750. if (this.finalMerge) {
  61751. this.finalMerge.dispose(camera);
  61752. }
  61753. }
  61754. this.pass = null;
  61755. this.highlights = null;
  61756. this.blurX = null;
  61757. this.blurY = null;
  61758. this.copyBack = null;
  61759. this.imageProcessing = null;
  61760. this.fxaa = null;
  61761. this.finalMerge = null;
  61762. };
  61763. // Dispose
  61764. DefaultRenderingPipeline.prototype.dispose = function () {
  61765. this._disposePostProcesses();
  61766. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61767. _super.prototype.dispose.call(this);
  61768. };
  61769. // Serialize rendering pipeline
  61770. DefaultRenderingPipeline.prototype.serialize = function () {
  61771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61772. serializationObject.customType = "DefaultRenderingPipeline";
  61773. return serializationObject;
  61774. };
  61775. // Parse serialized pipeline
  61776. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61777. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61778. };
  61779. __decorate([
  61780. BABYLON.serialize()
  61781. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61782. __decorate([
  61783. BABYLON.serialize()
  61784. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61785. __decorate([
  61786. BABYLON.serialize()
  61787. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61788. __decorate([
  61789. BABYLON.serialize()
  61790. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61791. __decorate([
  61792. BABYLON.serialize()
  61793. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61794. __decorate([
  61795. BABYLON.serialize()
  61796. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61797. __decorate([
  61798. BABYLON.serialize()
  61799. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61800. __decorate([
  61801. BABYLON.serialize()
  61802. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61803. return DefaultRenderingPipeline;
  61804. }(BABYLON.PostProcessRenderPipeline));
  61805. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61806. })(BABYLON || (BABYLON = {}));
  61807. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61808. var BABYLON;
  61809. (function (BABYLON) {
  61810. var GeometryBufferRenderer = /** @class */ (function () {
  61811. function GeometryBufferRenderer(scene, ratio) {
  61812. if (ratio === void 0) { ratio = 1; }
  61813. this._enablePosition = false;
  61814. this._scene = scene;
  61815. this._ratio = ratio;
  61816. // Render target
  61817. this._createRenderTargets();
  61818. }
  61819. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61820. set: function (meshes) {
  61821. this._multiRenderTarget.renderList = meshes;
  61822. },
  61823. enumerable: true,
  61824. configurable: true
  61825. });
  61826. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61827. get: function () {
  61828. return this._multiRenderTarget.isSupported;
  61829. },
  61830. enumerable: true,
  61831. configurable: true
  61832. });
  61833. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61834. get: function () {
  61835. return this._enablePosition;
  61836. },
  61837. set: function (enable) {
  61838. this._enablePosition = enable;
  61839. this.dispose();
  61840. this._createRenderTargets();
  61841. },
  61842. enumerable: true,
  61843. configurable: true
  61844. });
  61845. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61846. var material = subMesh.getMaterial();
  61847. if (material && material.disableDepthWrite) {
  61848. return false;
  61849. }
  61850. var defines = [];
  61851. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61852. var mesh = subMesh.getMesh();
  61853. // Alpha test
  61854. if (material && material.needAlphaTesting()) {
  61855. defines.push("#define ALPHATEST");
  61856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61857. attribs.push(BABYLON.VertexBuffer.UVKind);
  61858. defines.push("#define UV1");
  61859. }
  61860. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61861. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61862. defines.push("#define UV2");
  61863. }
  61864. }
  61865. // Buffers
  61866. if (this._enablePosition) {
  61867. defines.push("#define POSITION");
  61868. }
  61869. // Bones
  61870. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61871. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61872. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61873. if (mesh.numBoneInfluencers > 4) {
  61874. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61875. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61876. }
  61877. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61878. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61879. }
  61880. else {
  61881. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61882. }
  61883. // Instances
  61884. if (useInstances) {
  61885. defines.push("#define INSTANCES");
  61886. attribs.push("world0");
  61887. attribs.push("world1");
  61888. attribs.push("world2");
  61889. attribs.push("world3");
  61890. }
  61891. // Get correct effect
  61892. var join = defines.join("\n");
  61893. if (this._cachedDefines !== join) {
  61894. this._cachedDefines = join;
  61895. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61896. }
  61897. return this._effect.isReady();
  61898. };
  61899. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61900. return this._multiRenderTarget;
  61901. };
  61902. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61903. get: function () {
  61904. return this._multiRenderTarget.samples;
  61905. },
  61906. set: function (value) {
  61907. this._multiRenderTarget.samples = value;
  61908. },
  61909. enumerable: true,
  61910. configurable: true
  61911. });
  61912. // Methods
  61913. GeometryBufferRenderer.prototype.dispose = function () {
  61914. this.getGBuffer().dispose();
  61915. };
  61916. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61917. var _this = this;
  61918. var engine = this._scene.getEngine();
  61919. var count = this._enablePosition ? 3 : 2;
  61920. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  61921. if (!this.isSupported) {
  61922. return;
  61923. }
  61924. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61925. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61926. this._multiRenderTarget.refreshRate = 1;
  61927. this._multiRenderTarget.renderParticles = false;
  61928. this._multiRenderTarget.renderList = null;
  61929. // set default depth value to 1.0 (far away)
  61930. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61931. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61932. });
  61933. // Custom render function
  61934. var renderSubMesh = function (subMesh) {
  61935. var mesh = subMesh.getRenderingMesh();
  61936. var scene = _this._scene;
  61937. var engine = scene.getEngine();
  61938. var material = subMesh.getMaterial();
  61939. if (!material) {
  61940. return;
  61941. }
  61942. // Culling
  61943. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61944. // Managing instances
  61945. var batch = mesh._getInstancesRenderList(subMesh._id);
  61946. if (batch.mustReturn) {
  61947. return;
  61948. }
  61949. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61950. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61951. engine.enableEffect(_this._effect);
  61952. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61953. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61954. _this._effect.setMatrix("view", scene.getViewMatrix());
  61955. // Alpha test
  61956. if (material && material.needAlphaTesting()) {
  61957. var alphaTexture = material.getAlphaTestTexture();
  61958. if (alphaTexture) {
  61959. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61960. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61961. }
  61962. }
  61963. // Bones
  61964. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61965. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61966. }
  61967. // Draw
  61968. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61969. }
  61970. };
  61971. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61972. var index;
  61973. if (depthOnlySubMeshes.length) {
  61974. engine.setColorWrite(false);
  61975. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61976. renderSubMesh(depthOnlySubMeshes.data[index]);
  61977. }
  61978. engine.setColorWrite(true);
  61979. }
  61980. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61981. renderSubMesh(opaqueSubMeshes.data[index]);
  61982. }
  61983. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61984. renderSubMesh(alphaTestSubMeshes.data[index]);
  61985. }
  61986. };
  61987. };
  61988. return GeometryBufferRenderer;
  61989. }());
  61990. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61991. })(BABYLON || (BABYLON = {}));
  61992. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61993. var BABYLON;
  61994. (function (BABYLON) {
  61995. var RefractionPostProcess = /** @class */ (function (_super) {
  61996. __extends(RefractionPostProcess, _super);
  61997. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61998. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61999. _this.color = color;
  62000. _this.depth = depth;
  62001. _this.colorLevel = colorLevel;
  62002. _this.onActivateObservable.add(function (cam) {
  62003. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  62004. });
  62005. _this.onApplyObservable.add(function (effect) {
  62006. effect.setColor3("baseColor", _this.color);
  62007. effect.setFloat("depth", _this.depth);
  62008. effect.setFloat("colorLevel", _this.colorLevel);
  62009. effect.setTexture("refractionSampler", _this._refRexture);
  62010. });
  62011. return _this;
  62012. }
  62013. // Methods
  62014. RefractionPostProcess.prototype.dispose = function (camera) {
  62015. if (this._refRexture) {
  62016. this._refRexture.dispose();
  62017. }
  62018. _super.prototype.dispose.call(this, camera);
  62019. };
  62020. return RefractionPostProcess;
  62021. }(BABYLON.PostProcess));
  62022. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62023. })(BABYLON || (BABYLON = {}));
  62024. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62025. var BABYLON;
  62026. (function (BABYLON) {
  62027. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62028. __extends(BlackAndWhitePostProcess, _super);
  62029. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62030. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62031. _this.degree = 1;
  62032. _this.onApplyObservable.add(function (effect) {
  62033. effect.setFloat("degree", _this.degree);
  62034. });
  62035. return _this;
  62036. }
  62037. return BlackAndWhitePostProcess;
  62038. }(BABYLON.PostProcess));
  62039. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62040. })(BABYLON || (BABYLON = {}));
  62041. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62042. var BABYLON;
  62043. (function (BABYLON) {
  62044. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62045. __extends(ConvolutionPostProcess, _super);
  62046. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62047. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62048. _this.kernel = kernel;
  62049. _this.onApply = function (effect) {
  62050. effect.setFloat2("screenSize", _this.width, _this.height);
  62051. effect.setArray("kernel", _this.kernel);
  62052. };
  62053. return _this;
  62054. }
  62055. // Statics
  62056. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62057. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62058. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62059. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62060. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62061. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62062. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62063. return ConvolutionPostProcess;
  62064. }(BABYLON.PostProcess));
  62065. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62066. })(BABYLON || (BABYLON = {}));
  62067. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62068. var BABYLON;
  62069. (function (BABYLON) {
  62070. var FilterPostProcess = /** @class */ (function (_super) {
  62071. __extends(FilterPostProcess, _super);
  62072. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62073. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62074. _this.kernelMatrix = kernelMatrix;
  62075. _this.onApply = function (effect) {
  62076. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62077. };
  62078. return _this;
  62079. }
  62080. return FilterPostProcess;
  62081. }(BABYLON.PostProcess));
  62082. BABYLON.FilterPostProcess = FilterPostProcess;
  62083. })(BABYLON || (BABYLON = {}));
  62084. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62085. var BABYLON;
  62086. (function (BABYLON) {
  62087. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62088. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62089. __extends(VolumetricLightScatteringPostProcess, _super);
  62090. /**
  62091. * @constructor
  62092. * @param {string} name - The post-process name
  62093. * @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)
  62094. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62095. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62096. * @param {number} samples - The post-process quality, default 100
  62097. * @param {number} samplingMode - The post-process filtering mode
  62098. * @param {BABYLON.Engine} engine - The babylon engine
  62099. * @param {boolean} reusable - If the post-process is reusable
  62100. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62101. */
  62102. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62103. if (samples === void 0) { samples = 100; }
  62104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62105. 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;
  62106. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62107. /**
  62108. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62109. * @type {Vector3}
  62110. */
  62111. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62112. /**
  62113. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62114. * @type {boolean}
  62115. */
  62116. _this.useCustomMeshPosition = false;
  62117. /**
  62118. * If the post-process should inverse the light scattering direction
  62119. * @type {boolean}
  62120. */
  62121. _this.invert = true;
  62122. /**
  62123. * Array containing the excluded meshes not rendered in the internal pass
  62124. */
  62125. _this.excludedMeshes = new Array();
  62126. /**
  62127. * Controls the overall intensity of the post-process
  62128. * @type {number}
  62129. */
  62130. _this.exposure = 0.3;
  62131. /**
  62132. * Dissipates each sample's contribution in range [0, 1]
  62133. * @type {number}
  62134. */
  62135. _this.decay = 0.96815;
  62136. /**
  62137. * Controls the overall intensity of each sample
  62138. * @type {number}
  62139. */
  62140. _this.weight = 0.58767;
  62141. /**
  62142. * Controls the density of each sample
  62143. * @type {number}
  62144. */
  62145. _this.density = 0.926;
  62146. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62147. engine = scene.getEngine();
  62148. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62149. // Configure mesh
  62150. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62151. // Configure
  62152. _this._createPass(scene, ratio.passRatio || ratio);
  62153. _this.onActivate = function (camera) {
  62154. if (!_this.isSupported) {
  62155. _this.dispose(camera);
  62156. }
  62157. _this.onActivate = null;
  62158. };
  62159. _this.onApplyObservable.add(function (effect) {
  62160. _this._updateMeshScreenCoordinates(scene);
  62161. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62162. effect.setFloat("exposure", _this.exposure);
  62163. effect.setFloat("decay", _this.decay);
  62164. effect.setFloat("weight", _this.weight);
  62165. effect.setFloat("density", _this.density);
  62166. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62167. });
  62168. return _this;
  62169. }
  62170. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62171. get: function () {
  62172. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62173. return false;
  62174. },
  62175. set: function (useDiffuseColor) {
  62176. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62177. },
  62178. enumerable: true,
  62179. configurable: true
  62180. });
  62181. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62182. return "VolumetricLightScatteringPostProcess";
  62183. };
  62184. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62185. var mesh = subMesh.getMesh();
  62186. // Render this.mesh as default
  62187. if (mesh === this.mesh && mesh.material) {
  62188. return mesh.material.isReady(mesh);
  62189. }
  62190. var defines = [];
  62191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62192. var material = subMesh.getMaterial();
  62193. // Alpha test
  62194. if (material) {
  62195. if (material.needAlphaTesting()) {
  62196. defines.push("#define ALPHATEST");
  62197. }
  62198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62199. attribs.push(BABYLON.VertexBuffer.UVKind);
  62200. defines.push("#define UV1");
  62201. }
  62202. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62203. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62204. defines.push("#define UV2");
  62205. }
  62206. }
  62207. // Bones
  62208. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62211. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62212. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62213. }
  62214. else {
  62215. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62216. }
  62217. // Instances
  62218. if (useInstances) {
  62219. defines.push("#define INSTANCES");
  62220. attribs.push("world0");
  62221. attribs.push("world1");
  62222. attribs.push("world2");
  62223. attribs.push("world3");
  62224. }
  62225. // Get correct effect
  62226. var join = defines.join("\n");
  62227. if (this._cachedDefines !== join) {
  62228. this._cachedDefines = join;
  62229. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62230. }
  62231. return this._volumetricLightScatteringPass.isReady();
  62232. };
  62233. /**
  62234. * Sets the new light position for light scattering effect
  62235. * @param {BABYLON.Vector3} The new custom light position
  62236. */
  62237. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62238. this.customMeshPosition = position;
  62239. };
  62240. /**
  62241. * Returns the light position for light scattering effect
  62242. * @return {BABYLON.Vector3} The custom light position
  62243. */
  62244. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62245. return this.customMeshPosition;
  62246. };
  62247. /**
  62248. * Disposes the internal assets and detaches the post-process from the camera
  62249. */
  62250. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62251. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62252. if (rttIndex !== -1) {
  62253. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62254. }
  62255. this._volumetricLightScatteringRTT.dispose();
  62256. _super.prototype.dispose.call(this, camera);
  62257. };
  62258. /**
  62259. * Returns the render target texture used by the post-process
  62260. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62261. */
  62262. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62263. return this._volumetricLightScatteringRTT;
  62264. };
  62265. // Private methods
  62266. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62267. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62268. return true;
  62269. }
  62270. return false;
  62271. };
  62272. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62273. var _this = this;
  62274. var engine = scene.getEngine();
  62275. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62276. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62277. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62278. this._volumetricLightScatteringRTT.renderList = null;
  62279. this._volumetricLightScatteringRTT.renderParticles = false;
  62280. var camera = this.getCamera();
  62281. if (camera) {
  62282. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62283. }
  62284. else {
  62285. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62286. }
  62287. // Custom render function for submeshes
  62288. var renderSubMesh = function (subMesh) {
  62289. var mesh = subMesh.getRenderingMesh();
  62290. if (_this._meshExcluded(mesh)) {
  62291. return;
  62292. }
  62293. var material = subMesh.getMaterial();
  62294. if (!material) {
  62295. return;
  62296. }
  62297. var scene = mesh.getScene();
  62298. var engine = scene.getEngine();
  62299. // Culling
  62300. engine.setState(material.backFaceCulling);
  62301. // Managing instances
  62302. var batch = mesh._getInstancesRenderList(subMesh._id);
  62303. if (batch.mustReturn) {
  62304. return;
  62305. }
  62306. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62307. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62308. var effect = _this._volumetricLightScatteringPass;
  62309. if (mesh === _this.mesh) {
  62310. if (subMesh.effect) {
  62311. effect = subMesh.effect;
  62312. }
  62313. else {
  62314. effect = material.getEffect();
  62315. }
  62316. }
  62317. engine.enableEffect(effect);
  62318. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62319. if (mesh === _this.mesh) {
  62320. material.bind(mesh.getWorldMatrix(), mesh);
  62321. }
  62322. else {
  62323. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62324. // Alpha test
  62325. if (material && material.needAlphaTesting()) {
  62326. var alphaTexture = material.getAlphaTestTexture();
  62327. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62328. if (alphaTexture) {
  62329. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62330. }
  62331. }
  62332. // Bones
  62333. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62334. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62335. }
  62336. }
  62337. // Draw
  62338. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62339. }
  62340. };
  62341. // Render target texture callbacks
  62342. var savedSceneClearColor;
  62343. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62344. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62345. savedSceneClearColor = scene.clearColor;
  62346. scene.clearColor = sceneClearColor;
  62347. });
  62348. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62349. scene.clearColor = savedSceneClearColor;
  62350. });
  62351. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62352. var engine = scene.getEngine();
  62353. var index;
  62354. if (depthOnlySubMeshes.length) {
  62355. engine.setColorWrite(false);
  62356. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62357. renderSubMesh(depthOnlySubMeshes.data[index]);
  62358. }
  62359. engine.setColorWrite(true);
  62360. }
  62361. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62362. renderSubMesh(opaqueSubMeshes.data[index]);
  62363. }
  62364. engine.setAlphaTesting(true);
  62365. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62366. renderSubMesh(alphaTestSubMeshes.data[index]);
  62367. }
  62368. engine.setAlphaTesting(false);
  62369. if (transparentSubMeshes.length) {
  62370. // Sort sub meshes
  62371. for (index = 0; index < transparentSubMeshes.length; index++) {
  62372. var submesh = transparentSubMeshes.data[index];
  62373. var boundingInfo = submesh.getBoundingInfo();
  62374. if (boundingInfo && scene.activeCamera) {
  62375. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62376. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62377. }
  62378. }
  62379. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62380. sortedArray.sort(function (a, b) {
  62381. // Alpha index first
  62382. if (a._alphaIndex > b._alphaIndex) {
  62383. return 1;
  62384. }
  62385. if (a._alphaIndex < b._alphaIndex) {
  62386. return -1;
  62387. }
  62388. // Then distance to camera
  62389. if (a._distanceToCamera < b._distanceToCamera) {
  62390. return 1;
  62391. }
  62392. if (a._distanceToCamera > b._distanceToCamera) {
  62393. return -1;
  62394. }
  62395. return 0;
  62396. });
  62397. // Render sub meshes
  62398. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62399. for (index = 0; index < sortedArray.length; index++) {
  62400. renderSubMesh(sortedArray[index]);
  62401. }
  62402. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62403. }
  62404. };
  62405. };
  62406. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62407. var transform = scene.getTransformMatrix();
  62408. var meshPosition;
  62409. if (this.useCustomMeshPosition) {
  62410. meshPosition = this.customMeshPosition;
  62411. }
  62412. else if (this.attachedNode) {
  62413. meshPosition = this.attachedNode.position;
  62414. }
  62415. else {
  62416. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62417. }
  62418. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62419. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62420. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62421. if (this.invert)
  62422. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62423. };
  62424. // Static methods
  62425. /**
  62426. * Creates a default mesh for the Volumeric Light Scattering post-process
  62427. * @param {string} The mesh name
  62428. * @param {BABYLON.Scene} The scene where to create the mesh
  62429. * @return {BABYLON.Mesh} the default mesh
  62430. */
  62431. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62432. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62433. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62434. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62435. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62436. mesh.material = material;
  62437. return mesh;
  62438. };
  62439. __decorate([
  62440. BABYLON.serializeAsVector3()
  62441. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62442. __decorate([
  62443. BABYLON.serialize()
  62444. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62445. __decorate([
  62446. BABYLON.serialize()
  62447. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62448. __decorate([
  62449. BABYLON.serializeAsMeshReference()
  62450. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62451. __decorate([
  62452. BABYLON.serialize()
  62453. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62454. __decorate([
  62455. BABYLON.serialize()
  62456. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62457. __decorate([
  62458. BABYLON.serialize()
  62459. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62460. __decorate([
  62461. BABYLON.serialize()
  62462. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62463. __decorate([
  62464. BABYLON.serialize()
  62465. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62466. return VolumetricLightScatteringPostProcess;
  62467. }(BABYLON.PostProcess));
  62468. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62469. })(BABYLON || (BABYLON = {}));
  62470. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62471. //
  62472. // This post-process allows the modification of rendered colors by using
  62473. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62474. //
  62475. // The object needs to be provided an url to a texture containing the color
  62476. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62477. // Use an image editing software to tweak the LUT to match your needs.
  62478. //
  62479. // For an example of a color LUT, see here:
  62480. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62481. // For explanations on color grading, see here:
  62482. // http://udn.epicgames.com/Three/ColorGrading.html
  62483. //
  62484. var BABYLON;
  62485. (function (BABYLON) {
  62486. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62487. __extends(ColorCorrectionPostProcess, _super);
  62488. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62489. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62490. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62491. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62492. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62493. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62494. _this.onApply = function (effect) {
  62495. effect.setTexture("colorTable", _this._colorTableTexture);
  62496. };
  62497. return _this;
  62498. }
  62499. return ColorCorrectionPostProcess;
  62500. }(BABYLON.PostProcess));
  62501. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62502. })(BABYLON || (BABYLON = {}));
  62503. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62504. var BABYLON;
  62505. (function (BABYLON) {
  62506. var TonemappingOperator;
  62507. (function (TonemappingOperator) {
  62508. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62509. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62510. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62511. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62512. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62513. ;
  62514. var TonemapPostProcess = /** @class */ (function (_super) {
  62515. __extends(TonemapPostProcess, _super);
  62516. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62518. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62519. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62520. _this._operator = _operator;
  62521. _this.exposureAdjustment = exposureAdjustment;
  62522. var defines = "#define ";
  62523. if (_this._operator === TonemappingOperator.Hable)
  62524. defines += "HABLE_TONEMAPPING";
  62525. else if (_this._operator === TonemappingOperator.Reinhard)
  62526. defines += "REINHARD_TONEMAPPING";
  62527. else if (_this._operator === TonemappingOperator.HejiDawson)
  62528. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62529. else if (_this._operator === TonemappingOperator.Photographic)
  62530. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62531. //sadly a second call to create the effect.
  62532. _this.updateEffect(defines);
  62533. _this.onApply = function (effect) {
  62534. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62535. };
  62536. return _this;
  62537. }
  62538. return TonemapPostProcess;
  62539. }(BABYLON.PostProcess));
  62540. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62541. })(BABYLON || (BABYLON = {}));
  62542. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62543. var BABYLON;
  62544. (function (BABYLON) {
  62545. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62546. __extends(DisplayPassPostProcess, _super);
  62547. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62548. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62549. }
  62550. return DisplayPassPostProcess;
  62551. }(BABYLON.PostProcess));
  62552. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62553. })(BABYLON || (BABYLON = {}));
  62554. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62555. var BABYLON;
  62556. (function (BABYLON) {
  62557. var HighlightsPostProcess = /** @class */ (function (_super) {
  62558. __extends(HighlightsPostProcess, _super);
  62559. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62561. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62562. }
  62563. return HighlightsPostProcess;
  62564. }(BABYLON.PostProcess));
  62565. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62566. })(BABYLON || (BABYLON = {}));
  62567. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62568. var BABYLON;
  62569. (function (BABYLON) {
  62570. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62571. __extends(ImageProcessingPostProcess, _super);
  62572. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62573. if (camera === void 0) { camera = null; }
  62574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62575. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62576. _this._fromLinearSpace = true;
  62577. /**
  62578. * Defines cache preventing GC.
  62579. */
  62580. _this._defines = {
  62581. IMAGEPROCESSING: false,
  62582. VIGNETTE: false,
  62583. VIGNETTEBLENDMODEMULTIPLY: false,
  62584. VIGNETTEBLENDMODEOPAQUE: false,
  62585. TONEMAPPING: false,
  62586. CONTRAST: false,
  62587. COLORCURVES: false,
  62588. COLORGRADING: false,
  62589. COLORGRADING3D: false,
  62590. FROMLINEARSPACE: false,
  62591. SAMPLER3DGREENDEPTH: false,
  62592. SAMPLER3DBGRMAP: false,
  62593. IMAGEPROCESSINGPOSTPROCESS: false,
  62594. EXPOSURE: false,
  62595. };
  62596. // Setup the configuration as forced by the constructor. This would then not force the
  62597. // scene materials output in linear space and let untouched the default forward pass.
  62598. if (imageProcessingConfiguration) {
  62599. imageProcessingConfiguration.applyByPostProcess = true;
  62600. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62601. // This will cause the shader to be compiled
  62602. _this.fromLinearSpace = false;
  62603. }
  62604. else {
  62605. _this._attachImageProcessingConfiguration(null, true);
  62606. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62607. }
  62608. _this.onApply = function (effect) {
  62609. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62610. };
  62611. return _this;
  62612. }
  62613. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62614. /**
  62615. * Gets the image processing configuration used either in this material.
  62616. */
  62617. get: function () {
  62618. return this._imageProcessingConfiguration;
  62619. },
  62620. /**
  62621. * Sets the Default image processing configuration used either in the this material.
  62622. *
  62623. * If sets to null, the scene one is in use.
  62624. */
  62625. set: function (value) {
  62626. this._attachImageProcessingConfiguration(value);
  62627. },
  62628. enumerable: true,
  62629. configurable: true
  62630. });
  62631. /**
  62632. * Attaches a new image processing configuration to the PBR Material.
  62633. * @param configuration
  62634. */
  62635. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62636. var _this = this;
  62637. if (doNotBuild === void 0) { doNotBuild = false; }
  62638. if (configuration === this._imageProcessingConfiguration) {
  62639. return;
  62640. }
  62641. // Detaches observer.
  62642. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62643. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62644. }
  62645. // Pick the scene configuration if needed.
  62646. if (!configuration) {
  62647. var scene = null;
  62648. var engine = this.getEngine();
  62649. var camera = this.getCamera();
  62650. if (camera) {
  62651. scene = camera.getScene();
  62652. }
  62653. else if (engine && engine.scenes) {
  62654. var scenes = engine.scenes;
  62655. scene = scenes[scenes.length - 1];
  62656. }
  62657. else {
  62658. scene = BABYLON.Engine.LastCreatedScene;
  62659. }
  62660. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62661. }
  62662. else {
  62663. this._imageProcessingConfiguration = configuration;
  62664. }
  62665. // Attaches observer.
  62666. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62667. _this._updateParameters();
  62668. });
  62669. // Ensure the effect will be rebuilt.
  62670. if (!doNotBuild) {
  62671. this._updateParameters();
  62672. }
  62673. };
  62674. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62675. /**
  62676. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62677. */
  62678. get: function () {
  62679. return this.imageProcessingConfiguration.colorCurves;
  62680. },
  62681. /**
  62682. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62683. */
  62684. set: function (value) {
  62685. this.imageProcessingConfiguration.colorCurves = value;
  62686. },
  62687. enumerable: true,
  62688. configurable: true
  62689. });
  62690. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62691. /**
  62692. * Gets wether the color curves effect is enabled.
  62693. */
  62694. get: function () {
  62695. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62696. },
  62697. /**
  62698. * Sets wether the color curves effect is enabled.
  62699. */
  62700. set: function (value) {
  62701. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62702. },
  62703. enumerable: true,
  62704. configurable: true
  62705. });
  62706. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62707. /**
  62708. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62709. */
  62710. get: function () {
  62711. return this.imageProcessingConfiguration.colorGradingTexture;
  62712. },
  62713. /**
  62714. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62715. */
  62716. set: function (value) {
  62717. this.imageProcessingConfiguration.colorGradingTexture = value;
  62718. },
  62719. enumerable: true,
  62720. configurable: true
  62721. });
  62722. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62723. /**
  62724. * Gets wether the color grading effect is enabled.
  62725. */
  62726. get: function () {
  62727. return this.imageProcessingConfiguration.colorGradingEnabled;
  62728. },
  62729. /**
  62730. * Gets wether the color grading effect is enabled.
  62731. */
  62732. set: function (value) {
  62733. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62734. },
  62735. enumerable: true,
  62736. configurable: true
  62737. });
  62738. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62739. /**
  62740. * Gets exposure used in the effect.
  62741. */
  62742. get: function () {
  62743. return this.imageProcessingConfiguration.exposure;
  62744. },
  62745. /**
  62746. * Sets exposure used in the effect.
  62747. */
  62748. set: function (value) {
  62749. this.imageProcessingConfiguration.exposure = value;
  62750. },
  62751. enumerable: true,
  62752. configurable: true
  62753. });
  62754. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62755. /**
  62756. * Gets wether tonemapping is enabled or not.
  62757. */
  62758. get: function () {
  62759. return this._imageProcessingConfiguration.toneMappingEnabled;
  62760. },
  62761. /**
  62762. * Sets wether tonemapping is enabled or not
  62763. */
  62764. set: function (value) {
  62765. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62766. },
  62767. enumerable: true,
  62768. configurable: true
  62769. });
  62770. ;
  62771. ;
  62772. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62773. /**
  62774. * Gets contrast used in the effect.
  62775. */
  62776. get: function () {
  62777. return this.imageProcessingConfiguration.contrast;
  62778. },
  62779. /**
  62780. * Sets contrast used in the effect.
  62781. */
  62782. set: function (value) {
  62783. this.imageProcessingConfiguration.contrast = value;
  62784. },
  62785. enumerable: true,
  62786. configurable: true
  62787. });
  62788. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62789. /**
  62790. * Gets Vignette stretch size.
  62791. */
  62792. get: function () {
  62793. return this.imageProcessingConfiguration.vignetteStretch;
  62794. },
  62795. /**
  62796. * Sets Vignette stretch size.
  62797. */
  62798. set: function (value) {
  62799. this.imageProcessingConfiguration.vignetteStretch = value;
  62800. },
  62801. enumerable: true,
  62802. configurable: true
  62803. });
  62804. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62805. /**
  62806. * Gets Vignette centre X Offset.
  62807. */
  62808. get: function () {
  62809. return this.imageProcessingConfiguration.vignetteCentreX;
  62810. },
  62811. /**
  62812. * Sets Vignette centre X Offset.
  62813. */
  62814. set: function (value) {
  62815. this.imageProcessingConfiguration.vignetteCentreX = value;
  62816. },
  62817. enumerable: true,
  62818. configurable: true
  62819. });
  62820. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62821. /**
  62822. * Gets Vignette centre Y Offset.
  62823. */
  62824. get: function () {
  62825. return this.imageProcessingConfiguration.vignetteCentreY;
  62826. },
  62827. /**
  62828. * Sets Vignette centre Y Offset.
  62829. */
  62830. set: function (value) {
  62831. this.imageProcessingConfiguration.vignetteCentreY = value;
  62832. },
  62833. enumerable: true,
  62834. configurable: true
  62835. });
  62836. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62837. /**
  62838. * Gets Vignette weight or intensity of the vignette effect.
  62839. */
  62840. get: function () {
  62841. return this.imageProcessingConfiguration.vignetteWeight;
  62842. },
  62843. /**
  62844. * Sets Vignette weight or intensity of the vignette effect.
  62845. */
  62846. set: function (value) {
  62847. this.imageProcessingConfiguration.vignetteWeight = value;
  62848. },
  62849. enumerable: true,
  62850. configurable: true
  62851. });
  62852. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62853. /**
  62854. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62855. * if vignetteEnabled is set to true.
  62856. */
  62857. get: function () {
  62858. return this.imageProcessingConfiguration.vignetteColor;
  62859. },
  62860. /**
  62861. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62862. * if vignetteEnabled is set to true.
  62863. */
  62864. set: function (value) {
  62865. this.imageProcessingConfiguration.vignetteColor = value;
  62866. },
  62867. enumerable: true,
  62868. configurable: true
  62869. });
  62870. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62871. /**
  62872. * Gets Camera field of view used by the Vignette effect.
  62873. */
  62874. get: function () {
  62875. return this.imageProcessingConfiguration.vignetteCameraFov;
  62876. },
  62877. /**
  62878. * Sets Camera field of view used by the Vignette effect.
  62879. */
  62880. set: function (value) {
  62881. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62882. },
  62883. enumerable: true,
  62884. configurable: true
  62885. });
  62886. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62887. /**
  62888. * Gets the vignette blend mode allowing different kind of effect.
  62889. */
  62890. get: function () {
  62891. return this.imageProcessingConfiguration.vignetteBlendMode;
  62892. },
  62893. /**
  62894. * Sets the vignette blend mode allowing different kind of effect.
  62895. */
  62896. set: function (value) {
  62897. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62898. },
  62899. enumerable: true,
  62900. configurable: true
  62901. });
  62902. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62903. /**
  62904. * Gets wether the vignette effect is enabled.
  62905. */
  62906. get: function () {
  62907. return this.imageProcessingConfiguration.vignetteEnabled;
  62908. },
  62909. /**
  62910. * Sets wether the vignette effect is enabled.
  62911. */
  62912. set: function (value) {
  62913. this.imageProcessingConfiguration.vignetteEnabled = value;
  62914. },
  62915. enumerable: true,
  62916. configurable: true
  62917. });
  62918. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62919. /**
  62920. * Gets wether the input of the processing is in Gamma or Linear Space.
  62921. */
  62922. get: function () {
  62923. return this._fromLinearSpace;
  62924. },
  62925. /**
  62926. * Sets wether the input of the processing is in Gamma or Linear Space.
  62927. */
  62928. set: function (value) {
  62929. if (this._fromLinearSpace === value) {
  62930. return;
  62931. }
  62932. this._fromLinearSpace = value;
  62933. this._updateParameters();
  62934. },
  62935. enumerable: true,
  62936. configurable: true
  62937. });
  62938. ImageProcessingPostProcess.prototype.getClassName = function () {
  62939. return "ImageProcessingPostProcess";
  62940. };
  62941. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62942. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62943. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62944. var defines = "";
  62945. for (var define in this._defines) {
  62946. if (this._defines[define]) {
  62947. defines += "#define " + define + ";\r\n";
  62948. }
  62949. }
  62950. var samplers = ["textureSampler"];
  62951. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62952. var uniforms = ["scale"];
  62953. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62954. this.updateEffect(defines, uniforms, samplers);
  62955. };
  62956. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62957. _super.prototype.dispose.call(this, camera);
  62958. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62959. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62960. }
  62961. this.imageProcessingConfiguration.applyByPostProcess = false;
  62962. };
  62963. __decorate([
  62964. BABYLON.serialize()
  62965. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62966. return ImageProcessingPostProcess;
  62967. }(BABYLON.PostProcess));
  62968. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62969. })(BABYLON || (BABYLON = {}));
  62970. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62971. var BABYLON;
  62972. (function (BABYLON) {
  62973. var BlurPostProcess = /** @class */ (function (_super) {
  62974. __extends(BlurPostProcess, _super);
  62975. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62977. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62978. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62979. _this.direction = direction;
  62980. _this._packedFloat = false;
  62981. _this.onApplyObservable.add(function (effect) {
  62982. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62983. });
  62984. _this.kernel = kernel;
  62985. return _this;
  62986. }
  62987. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62988. /**
  62989. * Gets the length in pixels of the blur sample region
  62990. */
  62991. get: function () {
  62992. return this._idealKernel;
  62993. },
  62994. /**
  62995. * Sets the length in pixels of the blur sample region
  62996. */
  62997. set: function (v) {
  62998. if (this._idealKernel === v) {
  62999. return;
  63000. }
  63001. v = Math.max(v, 1);
  63002. this._idealKernel = v;
  63003. this._kernel = this._nearestBestKernel(v);
  63004. this._updateParameters();
  63005. },
  63006. enumerable: true,
  63007. configurable: true
  63008. });
  63009. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  63010. /**
  63011. * Gets wether or not the blur is unpacking/repacking floats
  63012. */
  63013. get: function () {
  63014. return this._packedFloat;
  63015. },
  63016. /**
  63017. * Sets wether or not the blur needs to unpack/repack floats
  63018. */
  63019. set: function (v) {
  63020. if (this._packedFloat === v) {
  63021. return;
  63022. }
  63023. this._packedFloat = v;
  63024. this._updateParameters();
  63025. },
  63026. enumerable: true,
  63027. configurable: true
  63028. });
  63029. BlurPostProcess.prototype._updateParameters = function () {
  63030. // Generate sampling offsets and weights
  63031. var N = this._kernel;
  63032. var centerIndex = (N - 1) / 2;
  63033. // Generate Gaussian sampling weights over kernel
  63034. var offsets = [];
  63035. var weights = [];
  63036. var totalWeight = 0;
  63037. for (var i = 0; i < N; i++) {
  63038. var u = i / (N - 1);
  63039. var w = this._gaussianWeight(u * 2.0 - 1);
  63040. offsets[i] = (i - centerIndex);
  63041. weights[i] = w;
  63042. totalWeight += w;
  63043. }
  63044. // Normalize weights
  63045. for (var i = 0; i < weights.length; i++) {
  63046. weights[i] /= totalWeight;
  63047. }
  63048. // Optimize: combine samples to take advantage of hardware linear sampling
  63049. // Walk from left to center, combining pairs (symmetrically)
  63050. var linearSamplingWeights = [];
  63051. var linearSamplingOffsets = [];
  63052. var linearSamplingMap = [];
  63053. for (var i = 0; i <= centerIndex; i += 2) {
  63054. var j = Math.min(i + 1, Math.floor(centerIndex));
  63055. var singleCenterSample = i === j;
  63056. if (singleCenterSample) {
  63057. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63058. }
  63059. else {
  63060. var sharedCell = j === centerIndex;
  63061. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63062. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63063. if (offsetLinear === 0) {
  63064. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63065. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63066. }
  63067. else {
  63068. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63069. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63070. }
  63071. }
  63072. }
  63073. for (var i = 0; i < linearSamplingMap.length; i++) {
  63074. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63075. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63076. }
  63077. // Replace with optimized
  63078. offsets = linearSamplingOffsets;
  63079. weights = linearSamplingWeights;
  63080. // Generate shaders
  63081. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63082. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63083. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63084. var defines = "";
  63085. for (var i = 0; i < varyingCount; i++) {
  63086. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63087. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63088. }
  63089. var depCount = 0;
  63090. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63091. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63092. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63093. depCount++;
  63094. }
  63095. if (this.packedFloat) {
  63096. defines += "#define PACKEDFLOAT 1";
  63097. }
  63098. this.updateEffect(defines, null, null, {
  63099. varyingCount: varyingCount,
  63100. depCount: depCount
  63101. });
  63102. };
  63103. /**
  63104. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63105. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63106. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63107. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63108. * The gaps between physical kernels are compensated for in the weighting of the samples
  63109. * @param idealKernel Ideal blur kernel.
  63110. * @return Nearest best kernel.
  63111. */
  63112. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63113. var v = Math.round(idealKernel);
  63114. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63115. var k = _a[_i];
  63116. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63117. return Math.max(k, 3);
  63118. }
  63119. }
  63120. return Math.max(v, 3);
  63121. };
  63122. /**
  63123. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63124. * @param x The point on the Gaussian distribution to sample.
  63125. * @return the value of the Gaussian function at x.
  63126. */
  63127. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63128. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63129. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63130. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63131. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63132. // truncated at around 1.3% of peak strength.
  63133. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63134. var sigma = (1 / 3);
  63135. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63136. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63137. var weight = (1.0 / denominator) * Math.exp(exponent);
  63138. return weight;
  63139. };
  63140. /**
  63141. * Generates a string that can be used as a floating point number in GLSL.
  63142. * @param x Value to print.
  63143. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63144. * @return GLSL float string.
  63145. */
  63146. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63147. if (decimalFigures === void 0) { decimalFigures = 8; }
  63148. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63149. };
  63150. return BlurPostProcess;
  63151. }(BABYLON.PostProcess));
  63152. BABYLON.BlurPostProcess = BlurPostProcess;
  63153. })(BABYLON || (BABYLON = {}));
  63154. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63155. var BABYLON;
  63156. (function (BABYLON) {
  63157. var Bone = /** @class */ (function (_super) {
  63158. __extends(Bone, _super);
  63159. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63160. if (parentBone === void 0) { parentBone = null; }
  63161. if (localMatrix === void 0) { localMatrix = null; }
  63162. if (restPose === void 0) { restPose = null; }
  63163. if (baseMatrix === void 0) { baseMatrix = null; }
  63164. if (index === void 0) { index = null; }
  63165. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63166. _this.name = name;
  63167. _this.children = new Array();
  63168. _this.animations = new Array();
  63169. // Set this value to map this bone to a different index in the transform matrices.
  63170. // Set this value to -1 to exclude the bone from the transform matrices.
  63171. _this._index = null;
  63172. _this._worldTransform = new BABYLON.Matrix();
  63173. _this._absoluteTransform = new BABYLON.Matrix();
  63174. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63175. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63176. _this._scaleVector = BABYLON.Vector3.One();
  63177. _this._negateScaleChildren = BABYLON.Vector3.One();
  63178. _this._scalingDeterminant = 1;
  63179. _this._skeleton = skeleton;
  63180. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63181. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63182. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63183. _this._index = index;
  63184. skeleton.bones.push(_this);
  63185. _this.setParent(parentBone, false);
  63186. _this._updateDifferenceMatrix();
  63187. return _this;
  63188. }
  63189. Object.defineProperty(Bone.prototype, "_matrix", {
  63190. get: function () {
  63191. return this._localMatrix;
  63192. },
  63193. set: function (val) {
  63194. if (this._localMatrix) {
  63195. this._localMatrix.copyFrom(val);
  63196. }
  63197. else {
  63198. this._localMatrix = val;
  63199. }
  63200. },
  63201. enumerable: true,
  63202. configurable: true
  63203. });
  63204. // Members
  63205. Bone.prototype.getSkeleton = function () {
  63206. return this._skeleton;
  63207. };
  63208. Bone.prototype.getParent = function () {
  63209. return this._parent;
  63210. };
  63211. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63212. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63213. if (this._parent === parent) {
  63214. return;
  63215. }
  63216. if (this._parent) {
  63217. var index = this._parent.children.indexOf(this);
  63218. if (index !== -1) {
  63219. this._parent.children.splice(index, 1);
  63220. }
  63221. }
  63222. this._parent = parent;
  63223. if (this._parent) {
  63224. this._parent.children.push(this);
  63225. }
  63226. if (updateDifferenceMatrix) {
  63227. this._updateDifferenceMatrix();
  63228. }
  63229. };
  63230. Bone.prototype.getLocalMatrix = function () {
  63231. return this._localMatrix;
  63232. };
  63233. Bone.prototype.getBaseMatrix = function () {
  63234. return this._baseMatrix;
  63235. };
  63236. Bone.prototype.getRestPose = function () {
  63237. return this._restPose;
  63238. };
  63239. Bone.prototype.returnToRest = function () {
  63240. this.updateMatrix(this._restPose.clone());
  63241. };
  63242. Bone.prototype.getWorldMatrix = function () {
  63243. return this._worldTransform;
  63244. };
  63245. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63246. return this._invertedAbsoluteTransform;
  63247. };
  63248. Bone.prototype.getAbsoluteTransform = function () {
  63249. return this._absoluteTransform;
  63250. };
  63251. Object.defineProperty(Bone.prototype, "position", {
  63252. // Properties (matches AbstractMesh properties)
  63253. get: function () {
  63254. return this.getPosition();
  63255. },
  63256. set: function (newPosition) {
  63257. this.setPosition(newPosition);
  63258. },
  63259. enumerable: true,
  63260. configurable: true
  63261. });
  63262. Object.defineProperty(Bone.prototype, "rotation", {
  63263. get: function () {
  63264. return this.getRotation();
  63265. },
  63266. set: function (newRotation) {
  63267. this.setRotation(newRotation);
  63268. },
  63269. enumerable: true,
  63270. configurable: true
  63271. });
  63272. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63273. get: function () {
  63274. return this.getRotationQuaternion();
  63275. },
  63276. set: function (newRotation) {
  63277. this.setRotationQuaternion(newRotation);
  63278. },
  63279. enumerable: true,
  63280. configurable: true
  63281. });
  63282. Object.defineProperty(Bone.prototype, "scaling", {
  63283. get: function () {
  63284. return this.getScale();
  63285. },
  63286. set: function (newScaling) {
  63287. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. // Methods
  63293. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63294. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63295. this._baseMatrix = matrix.clone();
  63296. this._localMatrix = matrix.clone();
  63297. this._skeleton._markAsDirty();
  63298. if (updateDifferenceMatrix) {
  63299. this._updateDifferenceMatrix();
  63300. }
  63301. };
  63302. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63303. if (!rootMatrix) {
  63304. rootMatrix = this._baseMatrix;
  63305. }
  63306. if (this._parent) {
  63307. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63308. }
  63309. else {
  63310. this._absoluteTransform.copyFrom(rootMatrix);
  63311. }
  63312. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63313. for (var index = 0; index < this.children.length; index++) {
  63314. this.children[index]._updateDifferenceMatrix();
  63315. }
  63316. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63317. };
  63318. Bone.prototype.markAsDirty = function () {
  63319. this._currentRenderId++;
  63320. this._skeleton._markAsDirty();
  63321. };
  63322. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63323. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63324. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63325. // all animation may be coming from a library skeleton, so may need to create animation
  63326. if (this.animations.length === 0) {
  63327. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63328. this.animations[0].setKeys([]);
  63329. }
  63330. // get animation info / verify there is such a range from the source bone
  63331. var sourceRange = source.animations[0].getRange(rangeName);
  63332. if (!sourceRange) {
  63333. return false;
  63334. }
  63335. var from = sourceRange.from;
  63336. var to = sourceRange.to;
  63337. var sourceKeys = source.animations[0].getKeys();
  63338. // rescaling prep
  63339. var sourceBoneLength = source.length;
  63340. var sourceParent = source.getParent();
  63341. var parent = this.getParent();
  63342. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63343. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63344. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63345. var destKeys = this.animations[0].getKeys();
  63346. // loop vars declaration
  63347. var orig;
  63348. var origTranslation;
  63349. var mat;
  63350. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63351. orig = sourceKeys[key];
  63352. if (orig.frame >= from && orig.frame <= to) {
  63353. if (rescaleAsRequired) {
  63354. mat = orig.value.clone();
  63355. // scale based on parent ratio, when bone has parent
  63356. if (parentScalingReqd) {
  63357. origTranslation = mat.getTranslation();
  63358. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63359. // scale based on skeleton dimension ratio when root bone, and value is passed
  63360. }
  63361. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63362. origTranslation = mat.getTranslation();
  63363. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63364. // use original when root bone, and no data for skelDimensionsRatio
  63365. }
  63366. else {
  63367. mat = orig.value;
  63368. }
  63369. }
  63370. else {
  63371. mat = orig.value;
  63372. }
  63373. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63374. }
  63375. }
  63376. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63377. return true;
  63378. };
  63379. /**
  63380. * Translate the bone in local or world space.
  63381. * @param vec The amount to translate the bone.
  63382. * @param space The space that the translation is in.
  63383. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63384. */
  63385. Bone.prototype.translate = function (vec, space, mesh) {
  63386. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63387. var lm = this.getLocalMatrix();
  63388. if (space == BABYLON.Space.LOCAL) {
  63389. lm.m[12] += vec.x;
  63390. lm.m[13] += vec.y;
  63391. lm.m[14] += vec.z;
  63392. }
  63393. else {
  63394. var wm = null;
  63395. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63396. if (mesh) {
  63397. wm = mesh.getWorldMatrix();
  63398. }
  63399. this._skeleton.computeAbsoluteTransforms();
  63400. var tmat = Bone._tmpMats[0];
  63401. var tvec = Bone._tmpVecs[0];
  63402. if (this._parent) {
  63403. if (mesh && wm) {
  63404. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63405. tmat.multiplyToRef(wm, tmat);
  63406. }
  63407. else {
  63408. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63409. }
  63410. }
  63411. tmat.m[12] = 0;
  63412. tmat.m[13] = 0;
  63413. tmat.m[14] = 0;
  63414. tmat.invert();
  63415. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63416. lm.m[12] += tvec.x;
  63417. lm.m[13] += tvec.y;
  63418. lm.m[14] += tvec.z;
  63419. }
  63420. this.markAsDirty();
  63421. };
  63422. /**
  63423. * Set the postion of the bone in local or world space.
  63424. * @param position The position to set the bone.
  63425. * @param space The space that the position is in.
  63426. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63427. */
  63428. Bone.prototype.setPosition = function (position, space, mesh) {
  63429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63430. var lm = this.getLocalMatrix();
  63431. if (space == BABYLON.Space.LOCAL) {
  63432. lm.m[12] = position.x;
  63433. lm.m[13] = position.y;
  63434. lm.m[14] = position.z;
  63435. }
  63436. else {
  63437. var wm = null;
  63438. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63439. if (mesh) {
  63440. wm = mesh.getWorldMatrix();
  63441. }
  63442. this._skeleton.computeAbsoluteTransforms();
  63443. var tmat = Bone._tmpMats[0];
  63444. var vec = Bone._tmpVecs[0];
  63445. if (this._parent) {
  63446. if (mesh && wm) {
  63447. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63448. tmat.multiplyToRef(wm, tmat);
  63449. }
  63450. else {
  63451. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63452. }
  63453. }
  63454. tmat.invert();
  63455. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63456. lm.m[12] = vec.x;
  63457. lm.m[13] = vec.y;
  63458. lm.m[14] = vec.z;
  63459. }
  63460. this.markAsDirty();
  63461. };
  63462. /**
  63463. * Set the absolute postion of the bone (world space).
  63464. * @param position The position to set the bone.
  63465. * @param mesh The mesh that this bone is attached to.
  63466. */
  63467. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63468. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63469. };
  63470. /**
  63471. * Set the scale of the bone on the x, y and z axes.
  63472. * @param x The scale of the bone on the x axis.
  63473. * @param x The scale of the bone on the y axis.
  63474. * @param z The scale of the bone on the z axis.
  63475. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63476. */
  63477. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63478. if (scaleChildren === void 0) { scaleChildren = false; }
  63479. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63480. if (!scaleChildren) {
  63481. this._negateScaleChildren.x = 1 / x;
  63482. this._negateScaleChildren.y = 1 / y;
  63483. this._negateScaleChildren.z = 1 / z;
  63484. }
  63485. this._syncScaleVector();
  63486. }
  63487. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63488. };
  63489. /**
  63490. * Scale the bone on the x, y and z axes.
  63491. * @param x The amount to scale the bone on the x axis.
  63492. * @param x The amount to scale the bone on the y axis.
  63493. * @param z The amount to scale the bone on the z axis.
  63494. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63495. */
  63496. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63497. if (scaleChildren === void 0) { scaleChildren = false; }
  63498. var locMat = this.getLocalMatrix();
  63499. var origLocMat = Bone._tmpMats[0];
  63500. origLocMat.copyFrom(locMat);
  63501. var origLocMatInv = Bone._tmpMats[1];
  63502. origLocMatInv.copyFrom(origLocMat);
  63503. origLocMatInv.invert();
  63504. var scaleMat = Bone._tmpMats[2];
  63505. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63506. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63507. this._scaleVector.x *= x;
  63508. this._scaleVector.y *= y;
  63509. this._scaleVector.z *= z;
  63510. locMat.multiplyToRef(origLocMatInv, locMat);
  63511. locMat.multiplyToRef(scaleMat, locMat);
  63512. locMat.multiplyToRef(origLocMat, locMat);
  63513. var parent = this.getParent();
  63514. if (parent) {
  63515. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63516. }
  63517. else {
  63518. this.getAbsoluteTransform().copyFrom(locMat);
  63519. }
  63520. var len = this.children.length;
  63521. scaleMat.invert();
  63522. for (var i = 0; i < len; i++) {
  63523. var child = this.children[i];
  63524. var cm = child.getLocalMatrix();
  63525. cm.multiplyToRef(scaleMat, cm);
  63526. var lm = child.getLocalMatrix();
  63527. lm.m[12] *= x;
  63528. lm.m[13] *= y;
  63529. lm.m[14] *= z;
  63530. }
  63531. this.computeAbsoluteTransforms();
  63532. if (scaleChildren) {
  63533. for (var i = 0; i < len; i++) {
  63534. this.children[i].scale(x, y, z, scaleChildren);
  63535. }
  63536. }
  63537. this.markAsDirty();
  63538. };
  63539. /**
  63540. * Set the yaw, pitch, and roll of the bone in local or world space.
  63541. * @param yaw The rotation of the bone on the y axis.
  63542. * @param pitch The rotation of the bone on the x axis.
  63543. * @param roll The rotation of the bone on the z axis.
  63544. * @param space The space that the axes of rotation are in.
  63545. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63546. */
  63547. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63549. var rotMat = Bone._tmpMats[0];
  63550. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63551. var rotMatInv = Bone._tmpMats[1];
  63552. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63553. rotMatInv.multiplyToRef(rotMat, rotMat);
  63554. this._rotateWithMatrix(rotMat, space, mesh);
  63555. };
  63556. /**
  63557. * Rotate the bone on an axis in local or world space.
  63558. * @param axis The axis to rotate the bone on.
  63559. * @param amount The amount to rotate the bone.
  63560. * @param space The space that the axis is in.
  63561. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63562. */
  63563. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63565. var rmat = Bone._tmpMats[0];
  63566. rmat.m[12] = 0;
  63567. rmat.m[13] = 0;
  63568. rmat.m[14] = 0;
  63569. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63570. this._rotateWithMatrix(rmat, space, mesh);
  63571. };
  63572. /**
  63573. * Set the rotation of the bone to a particular axis angle in local or world space.
  63574. * @param axis The axis to rotate the bone on.
  63575. * @param angle The angle that the bone should be rotated to.
  63576. * @param space The space that the axis is in.
  63577. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63578. */
  63579. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63581. var rotMat = Bone._tmpMats[0];
  63582. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63583. var rotMatInv = Bone._tmpMats[1];
  63584. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63585. rotMatInv.multiplyToRef(rotMat, rotMat);
  63586. this._rotateWithMatrix(rotMat, space, mesh);
  63587. };
  63588. /**
  63589. * Set the euler rotation of the bone in local of world space.
  63590. * @param rotation The euler rotation that the bone should be set to.
  63591. * @param space The space that the rotation is in.
  63592. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63593. */
  63594. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63596. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63597. };
  63598. /**
  63599. * Set the quaternion rotation of the bone in local of world space.
  63600. * @param quat The quaternion rotation that the bone should be set to.
  63601. * @param space The space that the rotation is in.
  63602. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63603. */
  63604. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63605. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63606. var rotMatInv = Bone._tmpMats[0];
  63607. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63608. var rotMat = Bone._tmpMats[1];
  63609. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63610. rotMatInv.multiplyToRef(rotMat, rotMat);
  63611. this._rotateWithMatrix(rotMat, space, mesh);
  63612. };
  63613. /**
  63614. * Set the rotation matrix of the bone in local of world space.
  63615. * @param rotMat The rotation matrix that the bone should be set to.
  63616. * @param space The space that the rotation is in.
  63617. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63618. */
  63619. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63621. var rotMatInv = Bone._tmpMats[0];
  63622. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63623. var rotMat2 = Bone._tmpMats[1];
  63624. rotMat2.copyFrom(rotMat);
  63625. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63626. this._rotateWithMatrix(rotMat2, space, mesh);
  63627. };
  63628. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63629. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63630. var lmat = this.getLocalMatrix();
  63631. var lx = lmat.m[12];
  63632. var ly = lmat.m[13];
  63633. var lz = lmat.m[14];
  63634. var parent = this.getParent();
  63635. var parentScale = Bone._tmpMats[3];
  63636. var parentScaleInv = Bone._tmpMats[4];
  63637. if (parent) {
  63638. if (space == BABYLON.Space.WORLD) {
  63639. if (mesh) {
  63640. parentScale.copyFrom(mesh.getWorldMatrix());
  63641. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63642. }
  63643. else {
  63644. parentScale.copyFrom(parent.getAbsoluteTransform());
  63645. }
  63646. }
  63647. else {
  63648. parentScale = parent._scaleMatrix;
  63649. }
  63650. parentScaleInv.copyFrom(parentScale);
  63651. parentScaleInv.invert();
  63652. lmat.multiplyToRef(parentScale, lmat);
  63653. lmat.multiplyToRef(rmat, lmat);
  63654. lmat.multiplyToRef(parentScaleInv, lmat);
  63655. }
  63656. else {
  63657. if (space == BABYLON.Space.WORLD && mesh) {
  63658. parentScale.copyFrom(mesh.getWorldMatrix());
  63659. parentScaleInv.copyFrom(parentScale);
  63660. parentScaleInv.invert();
  63661. lmat.multiplyToRef(parentScale, lmat);
  63662. lmat.multiplyToRef(rmat, lmat);
  63663. lmat.multiplyToRef(parentScaleInv, lmat);
  63664. }
  63665. else {
  63666. lmat.multiplyToRef(rmat, lmat);
  63667. }
  63668. }
  63669. lmat.m[12] = lx;
  63670. lmat.m[13] = ly;
  63671. lmat.m[14] = lz;
  63672. this.computeAbsoluteTransforms();
  63673. this.markAsDirty();
  63674. };
  63675. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63676. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63677. if (space == BABYLON.Space.WORLD) {
  63678. var scaleMatrix = Bone._tmpMats[2];
  63679. scaleMatrix.copyFrom(this._scaleMatrix);
  63680. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63681. if (mesh) {
  63682. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63683. var meshScale = Bone._tmpMats[3];
  63684. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63685. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63686. }
  63687. rotMatInv.invert();
  63688. scaleMatrix.m[0] *= this._scalingDeterminant;
  63689. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63690. }
  63691. else {
  63692. rotMatInv.copyFrom(this.getLocalMatrix());
  63693. rotMatInv.invert();
  63694. var scaleMatrix = Bone._tmpMats[2];
  63695. scaleMatrix.copyFrom(this._scaleMatrix);
  63696. if (this._parent) {
  63697. var pscaleMatrix = Bone._tmpMats[3];
  63698. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63699. pscaleMatrix.invert();
  63700. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63701. }
  63702. else {
  63703. scaleMatrix.m[0] *= this._scalingDeterminant;
  63704. }
  63705. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63706. }
  63707. };
  63708. /**
  63709. * Get the scale of the bone
  63710. * @returns the scale of the bone
  63711. */
  63712. Bone.prototype.getScale = function () {
  63713. return this._scaleVector.clone();
  63714. };
  63715. /**
  63716. * Copy the scale of the bone to a vector3.
  63717. * @param result The vector3 to copy the scale to
  63718. */
  63719. Bone.prototype.getScaleToRef = function (result) {
  63720. result.copyFrom(this._scaleVector);
  63721. };
  63722. /**
  63723. * Get the position of the bone in local or world space.
  63724. * @param space The space that the returned position is in.
  63725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63726. * @returns The position of the bone
  63727. */
  63728. Bone.prototype.getPosition = function (space, mesh) {
  63729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63730. if (mesh === void 0) { mesh = null; }
  63731. var pos = BABYLON.Vector3.Zero();
  63732. this.getPositionToRef(space, mesh, pos);
  63733. return pos;
  63734. };
  63735. /**
  63736. * Copy the position of the bone to a vector3 in local or world space.
  63737. * @param space The space that the returned position is in.
  63738. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63739. * @param result The vector3 to copy the position to.
  63740. */
  63741. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63743. if (space == BABYLON.Space.LOCAL) {
  63744. var lm = this.getLocalMatrix();
  63745. result.x = lm.m[12];
  63746. result.y = lm.m[13];
  63747. result.z = lm.m[14];
  63748. }
  63749. else {
  63750. var wm = null;
  63751. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63752. if (mesh) {
  63753. wm = mesh.getWorldMatrix();
  63754. }
  63755. this._skeleton.computeAbsoluteTransforms();
  63756. var tmat = Bone._tmpMats[0];
  63757. if (mesh && wm) {
  63758. tmat.copyFrom(this.getAbsoluteTransform());
  63759. tmat.multiplyToRef(wm, tmat);
  63760. }
  63761. else {
  63762. tmat = this.getAbsoluteTransform();
  63763. }
  63764. result.x = tmat.m[12];
  63765. result.y = tmat.m[13];
  63766. result.z = tmat.m[14];
  63767. }
  63768. };
  63769. /**
  63770. * Get the absolute position of the bone (world space).
  63771. * @param mesh The mesh that this bone is attached to.
  63772. * @returns The absolute position of the bone
  63773. */
  63774. Bone.prototype.getAbsolutePosition = function (mesh) {
  63775. if (mesh === void 0) { mesh = null; }
  63776. var pos = BABYLON.Vector3.Zero();
  63777. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63778. return pos;
  63779. };
  63780. /**
  63781. * Copy the absolute position of the bone (world space) to the result param.
  63782. * @param mesh The mesh that this bone is attached to.
  63783. * @param result The vector3 to copy the absolute position to.
  63784. */
  63785. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63786. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63787. };
  63788. /**
  63789. * Compute the absolute transforms of this bone and its children.
  63790. */
  63791. Bone.prototype.computeAbsoluteTransforms = function () {
  63792. if (this._parent) {
  63793. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63794. }
  63795. else {
  63796. this._absoluteTransform.copyFrom(this._localMatrix);
  63797. var poseMatrix = this._skeleton.getPoseMatrix();
  63798. if (poseMatrix) {
  63799. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63800. }
  63801. }
  63802. var children = this.children;
  63803. var len = children.length;
  63804. for (var i = 0; i < len; i++) {
  63805. children[i].computeAbsoluteTransforms();
  63806. }
  63807. };
  63808. Bone.prototype._syncScaleVector = function () {
  63809. var lm = this.getLocalMatrix();
  63810. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63811. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63812. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63813. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63814. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63815. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63816. this._scaleVector.x = xs * Math.sqrt(xsq);
  63817. this._scaleVector.y = ys * Math.sqrt(ysq);
  63818. this._scaleVector.z = zs * Math.sqrt(zsq);
  63819. if (this._parent) {
  63820. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63821. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63822. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63823. }
  63824. 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);
  63825. };
  63826. /**
  63827. * Get the world direction from an axis that is in the local space of the bone.
  63828. * @param localAxis The local direction that is used to compute the world direction.
  63829. * @param mesh The mesh that this bone is attached to.
  63830. * @returns The world direction
  63831. */
  63832. Bone.prototype.getDirection = function (localAxis, mesh) {
  63833. if (mesh === void 0) { mesh = null; }
  63834. var result = BABYLON.Vector3.Zero();
  63835. this.getDirectionToRef(localAxis, mesh, result);
  63836. return result;
  63837. };
  63838. /**
  63839. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63840. * @param localAxis The local direction that is used to compute the world direction.
  63841. * @param mesh The mesh that this bone is attached to.
  63842. * @param result The vector3 that the world direction will be copied to.
  63843. */
  63844. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63845. if (mesh === void 0) { mesh = null; }
  63846. var wm = null;
  63847. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63848. if (mesh) {
  63849. wm = mesh.getWorldMatrix();
  63850. }
  63851. this._skeleton.computeAbsoluteTransforms();
  63852. var mat = Bone._tmpMats[0];
  63853. mat.copyFrom(this.getAbsoluteTransform());
  63854. if (mesh && wm) {
  63855. mat.multiplyToRef(wm, mat);
  63856. }
  63857. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63858. result.normalize();
  63859. };
  63860. /**
  63861. * Get the euler rotation of the bone in local or world space.
  63862. * @param space The space that the rotation should be in.
  63863. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63864. * @returns The euler rotation
  63865. */
  63866. Bone.prototype.getRotation = function (space, mesh) {
  63867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63868. if (mesh === void 0) { mesh = null; }
  63869. var result = BABYLON.Vector3.Zero();
  63870. this.getRotationToRef(space, mesh, result);
  63871. return result;
  63872. };
  63873. /**
  63874. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63875. * @param space The space that the rotation should be in.
  63876. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63877. * @param result The vector3 that the rotation should be copied to.
  63878. */
  63879. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63881. if (mesh === void 0) { mesh = null; }
  63882. var quat = Bone._tmpQuat;
  63883. this.getRotationQuaternionToRef(space, mesh, quat);
  63884. quat.toEulerAnglesToRef(result);
  63885. };
  63886. /**
  63887. * Get the quaternion rotation of the bone in either local or world space.
  63888. * @param space The space that the rotation should be in.
  63889. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63890. * @returns The quaternion rotation
  63891. */
  63892. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63893. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63894. if (mesh === void 0) { mesh = null; }
  63895. var result = BABYLON.Quaternion.Identity();
  63896. this.getRotationQuaternionToRef(space, mesh, result);
  63897. return result;
  63898. };
  63899. /**
  63900. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63901. * @param space The space that the rotation should be in.
  63902. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63903. * @param result The quaternion that the rotation should be copied to.
  63904. */
  63905. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63907. if (mesh === void 0) { mesh = null; }
  63908. if (space == BABYLON.Space.LOCAL) {
  63909. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63910. }
  63911. else {
  63912. var mat = Bone._tmpMats[0];
  63913. var amat = this.getAbsoluteTransform();
  63914. if (mesh) {
  63915. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63916. }
  63917. else {
  63918. mat.copyFrom(amat);
  63919. }
  63920. mat.m[0] *= this._scalingDeterminant;
  63921. mat.m[1] *= this._scalingDeterminant;
  63922. mat.m[2] *= this._scalingDeterminant;
  63923. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63924. }
  63925. };
  63926. /**
  63927. * Get the rotation matrix of the bone in local or world space.
  63928. * @param space The space that the rotation should be in.
  63929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63930. * @returns The rotation matrix
  63931. */
  63932. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63934. var result = BABYLON.Matrix.Identity();
  63935. this.getRotationMatrixToRef(space, mesh, result);
  63936. return result;
  63937. };
  63938. /**
  63939. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63940. * @param space The space that the rotation should be in.
  63941. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63942. * @param result The quaternion that the rotation should be copied to.
  63943. */
  63944. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63946. if (space == BABYLON.Space.LOCAL) {
  63947. this.getLocalMatrix().getRotationMatrixToRef(result);
  63948. }
  63949. else {
  63950. var mat = Bone._tmpMats[0];
  63951. var amat = this.getAbsoluteTransform();
  63952. if (mesh) {
  63953. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63954. }
  63955. else {
  63956. mat.copyFrom(amat);
  63957. }
  63958. mat.m[0] *= this._scalingDeterminant;
  63959. mat.m[1] *= this._scalingDeterminant;
  63960. mat.m[2] *= this._scalingDeterminant;
  63961. mat.getRotationMatrixToRef(result);
  63962. }
  63963. };
  63964. /**
  63965. * Get the world position of a point that is in the local space of the bone.
  63966. * @param position The local position
  63967. * @param mesh The mesh that this bone is attached to.
  63968. * @returns The world position
  63969. */
  63970. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63971. if (mesh === void 0) { mesh = null; }
  63972. var result = BABYLON.Vector3.Zero();
  63973. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63974. return result;
  63975. };
  63976. /**
  63977. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63978. * @param position The local position
  63979. * @param mesh The mesh that this bone is attached to.
  63980. * @param result The vector3 that the world position should be copied to.
  63981. */
  63982. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63983. if (mesh === void 0) { mesh = null; }
  63984. var wm = null;
  63985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63986. if (mesh) {
  63987. wm = mesh.getWorldMatrix();
  63988. }
  63989. this._skeleton.computeAbsoluteTransforms();
  63990. var tmat = Bone._tmpMats[0];
  63991. if (mesh && wm) {
  63992. tmat.copyFrom(this.getAbsoluteTransform());
  63993. tmat.multiplyToRef(wm, tmat);
  63994. }
  63995. else {
  63996. tmat = this.getAbsoluteTransform();
  63997. }
  63998. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63999. };
  64000. /**
  64001. * Get the local position of a point that is in world space.
  64002. * @param position The world position
  64003. * @param mesh The mesh that this bone is attached to.
  64004. * @returns The local position
  64005. */
  64006. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  64007. if (mesh === void 0) { mesh = null; }
  64008. var result = BABYLON.Vector3.Zero();
  64009. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  64010. return result;
  64011. };
  64012. /**
  64013. * Get the local position of a point that is in world space and copy it to the result param.
  64014. * @param position The world position
  64015. * @param mesh The mesh that this bone is attached to.
  64016. * @param result The vector3 that the local position should be copied to.
  64017. */
  64018. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64019. if (mesh === void 0) { mesh = null; }
  64020. var wm = null;
  64021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64022. if (mesh) {
  64023. wm = mesh.getWorldMatrix();
  64024. }
  64025. this._skeleton.computeAbsoluteTransforms();
  64026. var tmat = Bone._tmpMats[0];
  64027. tmat.copyFrom(this.getAbsoluteTransform());
  64028. if (mesh && wm) {
  64029. tmat.multiplyToRef(wm, tmat);
  64030. }
  64031. tmat.invert();
  64032. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64033. };
  64034. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64035. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64036. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64037. return Bone;
  64038. }(BABYLON.Node));
  64039. BABYLON.Bone = Bone;
  64040. })(BABYLON || (BABYLON = {}));
  64041. //# sourceMappingURL=babylon.bone.js.map
  64042. var BABYLON;
  64043. (function (BABYLON) {
  64044. var BoneIKController = /** @class */ (function () {
  64045. function BoneIKController(mesh, bone, options) {
  64046. this.targetPosition = BABYLON.Vector3.Zero();
  64047. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64048. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64049. this.poleAngle = 0;
  64050. this.slerpAmount = 1;
  64051. this._bone1Quat = BABYLON.Quaternion.Identity();
  64052. this._bone1Mat = BABYLON.Matrix.Identity();
  64053. this._bone2Ang = Math.PI;
  64054. this._maxAngle = Math.PI;
  64055. this._rightHandedSystem = false;
  64056. this._bendAxis = BABYLON.Vector3.Right();
  64057. this._slerping = false;
  64058. this._adjustRoll = 0;
  64059. this._bone2 = bone;
  64060. this._bone1 = bone.getParent();
  64061. if (!this._bone1) {
  64062. return;
  64063. }
  64064. this.mesh = mesh;
  64065. var bonePos = bone.getPosition();
  64066. if (bone.getAbsoluteTransform().determinant() > 0) {
  64067. this._rightHandedSystem = true;
  64068. this._bendAxis.x = 0;
  64069. this._bendAxis.y = 0;
  64070. this._bendAxis.z = -1;
  64071. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64072. this._adjustRoll = Math.PI * .5;
  64073. this._bendAxis.z = 1;
  64074. }
  64075. }
  64076. if (this._bone1.length) {
  64077. var boneScale1 = this._bone1.getScale();
  64078. var boneScale2 = this._bone2.getScale();
  64079. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64080. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64081. }
  64082. else if (this._bone1.children[0]) {
  64083. mesh.computeWorldMatrix(true);
  64084. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64085. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64086. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64087. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64088. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64089. }
  64090. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64091. this.maxAngle = Math.PI;
  64092. if (options) {
  64093. if (options.targetMesh) {
  64094. this.targetMesh = options.targetMesh;
  64095. this.targetMesh.computeWorldMatrix(true);
  64096. }
  64097. if (options.poleTargetMesh) {
  64098. this.poleTargetMesh = options.poleTargetMesh;
  64099. this.poleTargetMesh.computeWorldMatrix(true);
  64100. }
  64101. else if (options.poleTargetBone) {
  64102. this.poleTargetBone = options.poleTargetBone;
  64103. }
  64104. else if (this._bone1.getParent()) {
  64105. this.poleTargetBone = this._bone1.getParent();
  64106. }
  64107. if (options.poleTargetLocalOffset) {
  64108. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64109. }
  64110. if (options.poleAngle) {
  64111. this.poleAngle = options.poleAngle;
  64112. }
  64113. if (options.bendAxis) {
  64114. this._bendAxis.copyFrom(options.bendAxis);
  64115. }
  64116. if (options.maxAngle) {
  64117. this.maxAngle = options.maxAngle;
  64118. }
  64119. if (options.slerpAmount) {
  64120. this.slerpAmount = options.slerpAmount;
  64121. }
  64122. }
  64123. }
  64124. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64125. get: function () {
  64126. return this._maxAngle;
  64127. },
  64128. set: function (value) {
  64129. this._setMaxAngle(value);
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. BoneIKController.prototype._setMaxAngle = function (ang) {
  64135. if (ang < 0) {
  64136. ang = 0;
  64137. }
  64138. if (ang > Math.PI || ang == undefined) {
  64139. ang = Math.PI;
  64140. }
  64141. this._maxAngle = ang;
  64142. var a = this._bone1Length;
  64143. var b = this._bone2Length;
  64144. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64145. };
  64146. BoneIKController.prototype.update = function () {
  64147. var bone1 = this._bone1;
  64148. if (!bone1) {
  64149. return;
  64150. }
  64151. var target = this.targetPosition;
  64152. var poleTarget = this.poleTargetPosition;
  64153. var mat1 = BoneIKController._tmpMats[0];
  64154. var mat2 = BoneIKController._tmpMats[1];
  64155. if (this.targetMesh) {
  64156. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64157. }
  64158. if (this.poleTargetBone) {
  64159. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64160. }
  64161. else if (this.poleTargetMesh) {
  64162. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64163. }
  64164. var bonePos = BoneIKController._tmpVecs[0];
  64165. var zaxis = BoneIKController._tmpVecs[1];
  64166. var xaxis = BoneIKController._tmpVecs[2];
  64167. var yaxis = BoneIKController._tmpVecs[3];
  64168. var upAxis = BoneIKController._tmpVecs[4];
  64169. var _tmpQuat = BoneIKController._tmpQuat;
  64170. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64171. poleTarget.subtractToRef(bonePos, upAxis);
  64172. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64173. upAxis.y = 1;
  64174. }
  64175. else {
  64176. upAxis.normalize();
  64177. }
  64178. target.subtractToRef(bonePos, yaxis);
  64179. yaxis.normalize();
  64180. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64181. zaxis.normalize();
  64182. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64183. xaxis.normalize();
  64184. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64185. var a = this._bone1Length;
  64186. var b = this._bone2Length;
  64187. var c = BABYLON.Vector3.Distance(bonePos, target);
  64188. if (this._maxReach > 0) {
  64189. c = Math.min(this._maxReach, c);
  64190. }
  64191. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64192. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64193. if (acosa > 1) {
  64194. acosa = 1;
  64195. }
  64196. if (acosb > 1) {
  64197. acosb = 1;
  64198. }
  64199. if (acosa < -1) {
  64200. acosa = -1;
  64201. }
  64202. if (acosb < -1) {
  64203. acosb = -1;
  64204. }
  64205. var angA = Math.acos(acosa);
  64206. var angB = Math.acos(acosb);
  64207. var angC = -angA - angB;
  64208. if (this._rightHandedSystem) {
  64209. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64210. mat2.multiplyToRef(mat1, mat1);
  64211. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64212. mat2.multiplyToRef(mat1, mat1);
  64213. }
  64214. else {
  64215. var _tmpVec = BoneIKController._tmpVecs[5];
  64216. _tmpVec.copyFrom(this._bendAxis);
  64217. _tmpVec.x *= -1;
  64218. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64219. mat2.multiplyToRef(mat1, mat1);
  64220. }
  64221. if (this.poleAngle) {
  64222. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64223. mat1.multiplyToRef(mat2, mat1);
  64224. }
  64225. if (this._bone1) {
  64226. if (this.slerpAmount < 1) {
  64227. if (!this._slerping) {
  64228. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64229. }
  64230. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64231. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64232. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64233. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64234. this._slerping = true;
  64235. }
  64236. else {
  64237. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64238. this._bone1Mat.copyFrom(mat1);
  64239. this._slerping = false;
  64240. }
  64241. }
  64242. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64243. this._bone2Ang = angC;
  64244. };
  64245. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64246. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64247. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64248. return BoneIKController;
  64249. }());
  64250. BABYLON.BoneIKController = BoneIKController;
  64251. })(BABYLON || (BABYLON = {}));
  64252. //# sourceMappingURL=babylon.boneIKController.js.map
  64253. var BABYLON;
  64254. (function (BABYLON) {
  64255. var BoneLookController = /** @class */ (function () {
  64256. /**
  64257. * Create a BoneLookController
  64258. * @param mesh the mesh that the bone belongs to
  64259. * @param bone the bone that will be looking to the target
  64260. * @param target the target Vector3 to look at
  64261. * @param settings optional settings:
  64262. * - maxYaw: the maximum angle the bone will yaw to
  64263. * - minYaw: the minimum angle the bone will yaw to
  64264. * - maxPitch: the maximum angle the bone will pitch to
  64265. * - minPitch: the minimum angle the bone will yaw to
  64266. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64267. * - upAxis: the up axis of the coordinate system
  64268. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64269. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64270. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64271. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64272. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64273. * - adjustRoll: used to make an adjustment to the roll of the bone
  64274. **/
  64275. function BoneLookController(mesh, bone, target, options) {
  64276. /**
  64277. * The up axis of the coordinate system that is used when the bone is rotated.
  64278. */
  64279. this.upAxis = BABYLON.Vector3.Up();
  64280. /**
  64281. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64282. */
  64283. this.upAxisSpace = BABYLON.Space.LOCAL;
  64284. /**
  64285. * Used to make an adjustment to the yaw of the bone.
  64286. */
  64287. this.adjustYaw = 0;
  64288. /**
  64289. * Used to make an adjustment to the pitch of the bone.
  64290. */
  64291. this.adjustPitch = 0;
  64292. /**
  64293. * Used to make an adjustment to the roll of the bone.
  64294. */
  64295. this.adjustRoll = 0;
  64296. /**
  64297. * 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).
  64298. */
  64299. this.slerpAmount = 1;
  64300. this._boneQuat = BABYLON.Quaternion.Identity();
  64301. this._slerping = false;
  64302. this._firstFrameSkipped = false;
  64303. this._fowardAxis = BABYLON.Vector3.Forward();
  64304. this.mesh = mesh;
  64305. this.bone = bone;
  64306. this.target = target;
  64307. if (options) {
  64308. if (options.adjustYaw) {
  64309. this.adjustYaw = options.adjustYaw;
  64310. }
  64311. if (options.adjustPitch) {
  64312. this.adjustPitch = options.adjustPitch;
  64313. }
  64314. if (options.adjustRoll) {
  64315. this.adjustRoll = options.adjustRoll;
  64316. }
  64317. if (options.maxYaw != null) {
  64318. this.maxYaw = options.maxYaw;
  64319. }
  64320. else {
  64321. this.maxYaw = Math.PI;
  64322. }
  64323. if (options.minYaw != null) {
  64324. this.minYaw = options.minYaw;
  64325. }
  64326. else {
  64327. this.minYaw = -Math.PI;
  64328. }
  64329. if (options.maxPitch != null) {
  64330. this.maxPitch = options.maxPitch;
  64331. }
  64332. else {
  64333. this.maxPitch = Math.PI;
  64334. }
  64335. if (options.minPitch != null) {
  64336. this.minPitch = options.minPitch;
  64337. }
  64338. else {
  64339. this.minPitch = -Math.PI;
  64340. }
  64341. if (options.slerpAmount != null) {
  64342. this.slerpAmount = options.slerpAmount;
  64343. }
  64344. if (options.upAxis != null) {
  64345. this.upAxis = options.upAxis;
  64346. }
  64347. if (options.upAxisSpace != null) {
  64348. this.upAxisSpace = options.upAxisSpace;
  64349. }
  64350. if (options.yawAxis != null || options.pitchAxis != null) {
  64351. var newYawAxis = BABYLON.Axis.Y;
  64352. var newPitchAxis = BABYLON.Axis.X;
  64353. if (options.yawAxis != null) {
  64354. newYawAxis = options.yawAxis.clone();
  64355. newYawAxis.normalize();
  64356. }
  64357. if (options.pitchAxis != null) {
  64358. newPitchAxis = options.pitchAxis.clone();
  64359. newPitchAxis.normalize();
  64360. }
  64361. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64362. this._transformYawPitch = BABYLON.Matrix.Identity();
  64363. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64364. this._transformYawPitchInv = this._transformYawPitch.clone();
  64365. this._transformYawPitch.invert();
  64366. }
  64367. }
  64368. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64369. this.upAxisSpace = BABYLON.Space.LOCAL;
  64370. }
  64371. }
  64372. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64373. /**
  64374. * Get/set the minimum yaw angle that the bone can look to.
  64375. */
  64376. get: function () {
  64377. return this._minYaw;
  64378. },
  64379. set: function (value) {
  64380. this._minYaw = value;
  64381. this._minYawSin = Math.sin(value);
  64382. this._minYawCos = Math.cos(value);
  64383. if (this._maxYaw != null) {
  64384. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64385. this._yawRange = this._maxYaw - this._minYaw;
  64386. }
  64387. },
  64388. enumerable: true,
  64389. configurable: true
  64390. });
  64391. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64392. /**
  64393. * Get/set the maximum yaw angle that the bone can look to.
  64394. */
  64395. get: function () {
  64396. return this._maxYaw;
  64397. },
  64398. set: function (value) {
  64399. this._maxYaw = value;
  64400. this._maxYawSin = Math.sin(value);
  64401. this._maxYawCos = Math.cos(value);
  64402. if (this._minYaw != null) {
  64403. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64404. this._yawRange = this._maxYaw - this._minYaw;
  64405. }
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64411. /**
  64412. * Get/set the minimum pitch angle that the bone can look to.
  64413. */
  64414. get: function () {
  64415. return this._minPitch;
  64416. },
  64417. set: function (value) {
  64418. this._minPitch = value;
  64419. this._minPitchTan = Math.tan(value);
  64420. },
  64421. enumerable: true,
  64422. configurable: true
  64423. });
  64424. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64425. /**
  64426. * Get/set the maximum pitch angle that the bone can look to.
  64427. */
  64428. get: function () {
  64429. return this._maxPitch;
  64430. },
  64431. set: function (value) {
  64432. this._maxPitch = value;
  64433. this._maxPitchTan = Math.tan(value);
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. /**
  64439. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64440. */
  64441. BoneLookController.prototype.update = function () {
  64442. //skip the first frame when slerping so that the mesh rotation is correct
  64443. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64444. this._firstFrameSkipped = true;
  64445. return;
  64446. }
  64447. var bone = this.bone;
  64448. var bonePos = BoneLookController._tmpVecs[0];
  64449. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64450. var target = this.target;
  64451. var _tmpMat1 = BoneLookController._tmpMats[0];
  64452. var _tmpMat2 = BoneLookController._tmpMats[1];
  64453. var mesh = this.mesh;
  64454. var parentBone = bone.getParent();
  64455. var upAxis = BoneLookController._tmpVecs[1];
  64456. upAxis.copyFrom(this.upAxis);
  64457. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64458. if (this._transformYawPitch) {
  64459. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64460. }
  64461. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64462. }
  64463. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64464. mesh.getDirectionToRef(upAxis, upAxis);
  64465. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64466. upAxis.normalize();
  64467. }
  64468. }
  64469. var checkYaw = false;
  64470. var checkPitch = false;
  64471. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64472. checkYaw = true;
  64473. }
  64474. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64475. checkPitch = true;
  64476. }
  64477. if (checkYaw || checkPitch) {
  64478. var spaceMat = BoneLookController._tmpMats[2];
  64479. var spaceMatInv = BoneLookController._tmpMats[3];
  64480. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64481. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64482. }
  64483. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64484. spaceMat.copyFrom(mesh.getWorldMatrix());
  64485. }
  64486. else {
  64487. var forwardAxis = BoneLookController._tmpVecs[2];
  64488. forwardAxis.copyFrom(this._fowardAxis);
  64489. if (this._transformYawPitch) {
  64490. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64491. }
  64492. if (parentBone) {
  64493. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64494. }
  64495. else {
  64496. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64497. }
  64498. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64499. rightAxis.normalize();
  64500. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64501. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64502. }
  64503. spaceMat.invertToRef(spaceMatInv);
  64504. var xzlen = null;
  64505. if (checkPitch) {
  64506. var localTarget = BoneLookController._tmpVecs[3];
  64507. target.subtractToRef(bonePos, localTarget);
  64508. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64509. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64510. var pitch = Math.atan2(localTarget.y, xzlen);
  64511. var newPitch = pitch;
  64512. if (pitch > this._maxPitch) {
  64513. localTarget.y = this._maxPitchTan * xzlen;
  64514. newPitch = this._maxPitch;
  64515. }
  64516. else if (pitch < this._minPitch) {
  64517. localTarget.y = this._minPitchTan * xzlen;
  64518. newPitch = this._minPitch;
  64519. }
  64520. if (pitch != newPitch) {
  64521. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64522. localTarget.addInPlace(bonePos);
  64523. target = localTarget;
  64524. }
  64525. }
  64526. if (checkYaw) {
  64527. var localTarget = BoneLookController._tmpVecs[4];
  64528. target.subtractToRef(bonePos, localTarget);
  64529. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64530. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64531. var newYaw = yaw;
  64532. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64533. if (xzlen == null) {
  64534. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64535. }
  64536. if (this._yawRange > Math.PI) {
  64537. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64538. localTarget.z = this._maxYawCos * xzlen;
  64539. localTarget.x = this._maxYawSin * xzlen;
  64540. newYaw = this._maxYaw;
  64541. }
  64542. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64543. localTarget.z = this._minYawCos * xzlen;
  64544. localTarget.x = this._minYawSin * xzlen;
  64545. newYaw = this._minYaw;
  64546. }
  64547. }
  64548. else {
  64549. if (yaw > this._maxYaw) {
  64550. localTarget.z = this._maxYawCos * xzlen;
  64551. localTarget.x = this._maxYawSin * xzlen;
  64552. newYaw = this._maxYaw;
  64553. }
  64554. else if (yaw < this._minYaw) {
  64555. localTarget.z = this._minYawCos * xzlen;
  64556. localTarget.x = this._minYawSin * xzlen;
  64557. newYaw = this._minYaw;
  64558. }
  64559. }
  64560. }
  64561. if (this._slerping && this._yawRange > Math.PI) {
  64562. //are we going to be crossing into the min/max region?
  64563. var boneFwd = BoneLookController._tmpVecs[8];
  64564. boneFwd.copyFrom(BABYLON.Axis.Z);
  64565. if (this._transformYawPitch) {
  64566. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64567. }
  64568. var boneRotMat = BoneLookController._tmpMats[4];
  64569. this._boneQuat.toRotationMatrix(boneRotMat);
  64570. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64571. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64572. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64573. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64574. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64575. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64576. if (angBtwTar > angBtwMidYaw) {
  64577. if (xzlen == null) {
  64578. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64579. }
  64580. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64581. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64582. if (angBtwMin < angBtwMax) {
  64583. newYaw = boneYaw + Math.PI * .75;
  64584. localTarget.z = Math.cos(newYaw) * xzlen;
  64585. localTarget.x = Math.sin(newYaw) * xzlen;
  64586. }
  64587. else {
  64588. newYaw = boneYaw - Math.PI * .75;
  64589. localTarget.z = Math.cos(newYaw) * xzlen;
  64590. localTarget.x = Math.sin(newYaw) * xzlen;
  64591. }
  64592. }
  64593. }
  64594. if (yaw != newYaw) {
  64595. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64596. localTarget.addInPlace(bonePos);
  64597. target = localTarget;
  64598. }
  64599. }
  64600. }
  64601. var zaxis = BoneLookController._tmpVecs[5];
  64602. var xaxis = BoneLookController._tmpVecs[6];
  64603. var yaxis = BoneLookController._tmpVecs[7];
  64604. var _tmpQuat = BoneLookController._tmpQuat;
  64605. target.subtractToRef(bonePos, zaxis);
  64606. zaxis.normalize();
  64607. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64608. xaxis.normalize();
  64609. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64610. yaxis.normalize();
  64611. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64612. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64613. return;
  64614. }
  64615. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64616. return;
  64617. }
  64618. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64619. return;
  64620. }
  64621. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64622. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64623. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64624. }
  64625. if (this.slerpAmount < 1) {
  64626. if (!this._slerping) {
  64627. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64628. }
  64629. if (this._transformYawPitch) {
  64630. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64631. }
  64632. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64633. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64634. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64635. this._slerping = true;
  64636. }
  64637. else {
  64638. if (this._transformYawPitch) {
  64639. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64640. }
  64641. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64642. this._slerping = false;
  64643. }
  64644. };
  64645. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64646. var angDiff = ang2 - ang1;
  64647. angDiff %= Math.PI * 2;
  64648. if (angDiff > Math.PI) {
  64649. angDiff -= Math.PI * 2;
  64650. }
  64651. else if (angDiff < -Math.PI) {
  64652. angDiff += Math.PI * 2;
  64653. }
  64654. return angDiff;
  64655. };
  64656. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64657. ang1 %= (2 * Math.PI);
  64658. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64659. ang2 %= (2 * Math.PI);
  64660. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64661. var ab = 0;
  64662. if (ang1 < ang2) {
  64663. ab = ang2 - ang1;
  64664. }
  64665. else {
  64666. ab = ang1 - ang2;
  64667. }
  64668. if (ab > Math.PI) {
  64669. ab = Math.PI * 2 - ab;
  64670. }
  64671. return ab;
  64672. };
  64673. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64674. ang %= (2 * Math.PI);
  64675. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64676. ang1 %= (2 * Math.PI);
  64677. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64678. ang2 %= (2 * Math.PI);
  64679. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64680. if (ang1 < ang2) {
  64681. if (ang > ang1 && ang < ang2) {
  64682. return true;
  64683. }
  64684. }
  64685. else {
  64686. if (ang > ang2 && ang < ang1) {
  64687. return true;
  64688. }
  64689. }
  64690. return false;
  64691. };
  64692. 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()];
  64693. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64694. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64695. return BoneLookController;
  64696. }());
  64697. BABYLON.BoneLookController = BoneLookController;
  64698. })(BABYLON || (BABYLON = {}));
  64699. //# sourceMappingURL=babylon.boneLookController.js.map
  64700. var BABYLON;
  64701. (function (BABYLON) {
  64702. var Skeleton = /** @class */ (function () {
  64703. function Skeleton(name, id, scene) {
  64704. this.name = name;
  64705. this.id = id;
  64706. this.bones = new Array();
  64707. this.needInitialSkinMatrix = false;
  64708. this._isDirty = true;
  64709. this._meshesWithPoseMatrix = new Array();
  64710. this._identity = BABYLON.Matrix.Identity();
  64711. this._ranges = {};
  64712. this._lastAbsoluteTransformsUpdateId = -1;
  64713. // Events
  64714. /**
  64715. * An event triggered before computing the skeleton's matrices
  64716. * @type {BABYLON.Observable}
  64717. */
  64718. this.onBeforeComputeObservable = new BABYLON.Observable();
  64719. this.bones = [];
  64720. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64721. scene.skeletons.push(this);
  64722. //make sure it will recalculate the matrix next time prepare is called.
  64723. this._isDirty = true;
  64724. }
  64725. // Members
  64726. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64727. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64728. return mesh._bonesTransformMatrices;
  64729. }
  64730. if (!this._transformMatrices) {
  64731. this.prepare();
  64732. }
  64733. return this._transformMatrices;
  64734. };
  64735. Skeleton.prototype.getScene = function () {
  64736. return this._scene;
  64737. };
  64738. // Methods
  64739. /**
  64740. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64741. */
  64742. Skeleton.prototype.toString = function (fullDetails) {
  64743. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64744. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64745. if (fullDetails) {
  64746. ret += ", Ranges: {";
  64747. var first = true;
  64748. for (var name_1 in this._ranges) {
  64749. if (first) {
  64750. ret += ", ";
  64751. first = false;
  64752. }
  64753. ret += name_1;
  64754. }
  64755. ret += "}";
  64756. }
  64757. return ret;
  64758. };
  64759. /**
  64760. * Get bone's index searching by name
  64761. * @param {string} name is bone's name to search for
  64762. * @return {number} Indice of the bone. Returns -1 if not found
  64763. */
  64764. Skeleton.prototype.getBoneIndexByName = function (name) {
  64765. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64766. if (this.bones[boneIndex].name === name) {
  64767. return boneIndex;
  64768. }
  64769. }
  64770. return -1;
  64771. };
  64772. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64773. // check name not already in use
  64774. if (!this._ranges[name]) {
  64775. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64776. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64777. if (this.bones[i].animations[0]) {
  64778. this.bones[i].animations[0].createRange(name, from, to);
  64779. }
  64780. }
  64781. }
  64782. };
  64783. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64784. if (deleteFrames === void 0) { deleteFrames = true; }
  64785. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64786. if (this.bones[i].animations[0]) {
  64787. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64788. }
  64789. }
  64790. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64791. };
  64792. Skeleton.prototype.getAnimationRange = function (name) {
  64793. return this._ranges[name];
  64794. };
  64795. /**
  64796. * Returns as an Array, all AnimationRanges defined on this skeleton
  64797. */
  64798. Skeleton.prototype.getAnimationRanges = function () {
  64799. var animationRanges = [];
  64800. var name;
  64801. var i = 0;
  64802. for (name in this._ranges) {
  64803. animationRanges[i] = this._ranges[name];
  64804. i++;
  64805. }
  64806. return animationRanges;
  64807. };
  64808. /**
  64809. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64810. */
  64811. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64812. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64813. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64814. return false;
  64815. }
  64816. var ret = true;
  64817. var frameOffset = this._getHighestAnimationFrame() + 1;
  64818. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64819. var boneDict = {};
  64820. var sourceBones = source.bones;
  64821. var nBones;
  64822. var i;
  64823. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64824. boneDict[sourceBones[i].name] = sourceBones[i];
  64825. }
  64826. if (this.bones.length !== sourceBones.length) {
  64827. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64828. ret = false;
  64829. }
  64830. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64831. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64832. var boneName = this.bones[i].name;
  64833. var sourceBone = boneDict[boneName];
  64834. if (sourceBone) {
  64835. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64836. }
  64837. else {
  64838. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64839. ret = false;
  64840. }
  64841. }
  64842. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64843. var range = source.getAnimationRange(name);
  64844. if (range) {
  64845. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64846. }
  64847. return ret;
  64848. };
  64849. Skeleton.prototype.returnToRest = function () {
  64850. for (var index = 0; index < this.bones.length; index++) {
  64851. this.bones[index].returnToRest();
  64852. }
  64853. };
  64854. Skeleton.prototype._getHighestAnimationFrame = function () {
  64855. var ret = 0;
  64856. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64857. if (this.bones[i].animations[0]) {
  64858. var highest = this.bones[i].animations[0].getHighestFrame();
  64859. if (ret < highest) {
  64860. ret = highest;
  64861. }
  64862. }
  64863. }
  64864. return ret;
  64865. };
  64866. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64867. var range = this.getAnimationRange(name);
  64868. if (!range) {
  64869. return null;
  64870. }
  64871. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64872. };
  64873. Skeleton.prototype._markAsDirty = function () {
  64874. this._isDirty = true;
  64875. };
  64876. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64877. this._meshesWithPoseMatrix.push(mesh);
  64878. };
  64879. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64880. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64881. if (index > -1) {
  64882. this._meshesWithPoseMatrix.splice(index, 1);
  64883. }
  64884. };
  64885. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64886. this.onBeforeComputeObservable.notifyObservers(this);
  64887. for (var index = 0; index < this.bones.length; index++) {
  64888. var bone = this.bones[index];
  64889. var parentBone = bone.getParent();
  64890. if (parentBone) {
  64891. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64892. }
  64893. else {
  64894. if (initialSkinMatrix) {
  64895. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64896. }
  64897. else {
  64898. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64899. }
  64900. }
  64901. if (bone._index !== -1) {
  64902. var mappedIndex = bone._index === null ? index : bone._index;
  64903. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64904. }
  64905. }
  64906. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64907. };
  64908. Skeleton.prototype.prepare = function () {
  64909. if (!this._isDirty) {
  64910. return;
  64911. }
  64912. if (this.needInitialSkinMatrix) {
  64913. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64914. var mesh = this._meshesWithPoseMatrix[index];
  64915. var poseMatrix = mesh.getPoseMatrix();
  64916. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64917. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64918. }
  64919. if (this._synchronizedWithMesh !== mesh) {
  64920. this._synchronizedWithMesh = mesh;
  64921. // Prepare bones
  64922. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64923. var bone = this.bones[boneIndex];
  64924. if (!bone.getParent()) {
  64925. var matrix = bone.getBaseMatrix();
  64926. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64927. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64928. }
  64929. }
  64930. }
  64931. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64932. }
  64933. }
  64934. else {
  64935. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64936. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64937. }
  64938. this._computeTransformMatrices(this._transformMatrices, null);
  64939. }
  64940. this._isDirty = false;
  64941. this._scene._activeBones.addCount(this.bones.length, false);
  64942. };
  64943. Skeleton.prototype.getAnimatables = function () {
  64944. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64945. this._animatables = [];
  64946. for (var index = 0; index < this.bones.length; index++) {
  64947. this._animatables.push(this.bones[index]);
  64948. }
  64949. }
  64950. return this._animatables;
  64951. };
  64952. Skeleton.prototype.clone = function (name, id) {
  64953. var result = new Skeleton(name, id || name, this._scene);
  64954. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64955. for (var index = 0; index < this.bones.length; index++) {
  64956. var source = this.bones[index];
  64957. var parentBone = null;
  64958. var parent_1 = source.getParent();
  64959. if (parent_1) {
  64960. var parentIndex = this.bones.indexOf(parent_1);
  64961. parentBone = result.bones[parentIndex];
  64962. }
  64963. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64964. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64965. }
  64966. if (this._ranges) {
  64967. result._ranges = {};
  64968. for (var rangeName in this._ranges) {
  64969. var range = this._ranges[rangeName];
  64970. if (range) {
  64971. result._ranges[rangeName] = range.clone();
  64972. }
  64973. }
  64974. }
  64975. this._isDirty = true;
  64976. return result;
  64977. };
  64978. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64979. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64980. this.bones.forEach(function (bone) {
  64981. bone.animations.forEach(function (animation) {
  64982. animation.enableBlending = true;
  64983. animation.blendingSpeed = blendingSpeed;
  64984. });
  64985. });
  64986. };
  64987. Skeleton.prototype.dispose = function () {
  64988. this._meshesWithPoseMatrix = [];
  64989. // Animations
  64990. this.getScene().stopAnimation(this);
  64991. // Remove from scene
  64992. this.getScene().removeSkeleton(this);
  64993. };
  64994. Skeleton.prototype.serialize = function () {
  64995. var serializationObject = {};
  64996. serializationObject.name = this.name;
  64997. serializationObject.id = this.id;
  64998. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64999. serializationObject.bones = [];
  65000. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65001. for (var index = 0; index < this.bones.length; index++) {
  65002. var bone = this.bones[index];
  65003. var parent_2 = bone.getParent();
  65004. var serializedBone = {
  65005. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  65006. name: bone.name,
  65007. matrix: bone.getBaseMatrix().toArray(),
  65008. rest: bone.getRestPose().toArray()
  65009. };
  65010. serializationObject.bones.push(serializedBone);
  65011. if (bone.length) {
  65012. serializedBone.length = bone.length;
  65013. }
  65014. if (bone.animations && bone.animations.length > 0) {
  65015. serializedBone.animation = bone.animations[0].serialize();
  65016. }
  65017. serializationObject.ranges = [];
  65018. for (var name in this._ranges) {
  65019. var source = this._ranges[name];
  65020. if (!source) {
  65021. continue;
  65022. }
  65023. var range = {};
  65024. range.name = name;
  65025. range.from = source.from;
  65026. range.to = source.to;
  65027. serializationObject.ranges.push(range);
  65028. }
  65029. }
  65030. return serializationObject;
  65031. };
  65032. Skeleton.Parse = function (parsedSkeleton, scene) {
  65033. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65034. if (parsedSkeleton.dimensionsAtRest) {
  65035. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65036. }
  65037. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65038. var index;
  65039. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65040. var parsedBone = parsedSkeleton.bones[index];
  65041. var parentBone = null;
  65042. if (parsedBone.parentBoneIndex > -1) {
  65043. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65044. }
  65045. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65046. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65047. if (parsedBone.length) {
  65048. bone.length = parsedBone.length;
  65049. }
  65050. if (parsedBone.animation) {
  65051. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65052. }
  65053. }
  65054. // placed after bones, so createAnimationRange can cascade down
  65055. if (parsedSkeleton.ranges) {
  65056. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65057. var data = parsedSkeleton.ranges[index];
  65058. skeleton.createAnimationRange(data.name, data.from, data.to);
  65059. }
  65060. }
  65061. return skeleton;
  65062. };
  65063. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65064. if (forceUpdate === void 0) { forceUpdate = false; }
  65065. var renderId = this._scene.getRenderId();
  65066. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65067. this.bones[0].computeAbsoluteTransforms();
  65068. this._lastAbsoluteTransformsUpdateId = renderId;
  65069. }
  65070. };
  65071. Skeleton.prototype.getPoseMatrix = function () {
  65072. var poseMatrix = null;
  65073. if (this._meshesWithPoseMatrix.length > 0) {
  65074. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65075. }
  65076. return poseMatrix;
  65077. };
  65078. Skeleton.prototype.sortBones = function () {
  65079. var bones = new Array();
  65080. var visited = new Array(this.bones.length);
  65081. for (var index = 0; index < this.bones.length; index++) {
  65082. this._sortBones(index, bones, visited);
  65083. }
  65084. this.bones = bones;
  65085. };
  65086. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65087. if (visited[index]) {
  65088. return;
  65089. }
  65090. visited[index] = true;
  65091. var bone = this.bones[index];
  65092. if (bone._index === undefined) {
  65093. bone._index = index;
  65094. }
  65095. var parentBone = bone.getParent();
  65096. if (parentBone) {
  65097. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65098. }
  65099. bones.push(bone);
  65100. };
  65101. return Skeleton;
  65102. }());
  65103. BABYLON.Skeleton = Skeleton;
  65104. })(BABYLON || (BABYLON = {}));
  65105. //# sourceMappingURL=babylon.skeleton.js.map
  65106. var BABYLON;
  65107. (function (BABYLON) {
  65108. var SphericalPolynomial = /** @class */ (function () {
  65109. function SphericalPolynomial() {
  65110. this.x = BABYLON.Vector3.Zero();
  65111. this.y = BABYLON.Vector3.Zero();
  65112. this.z = BABYLON.Vector3.Zero();
  65113. this.xx = BABYLON.Vector3.Zero();
  65114. this.yy = BABYLON.Vector3.Zero();
  65115. this.zz = BABYLON.Vector3.Zero();
  65116. this.xy = BABYLON.Vector3.Zero();
  65117. this.yz = BABYLON.Vector3.Zero();
  65118. this.zx = BABYLON.Vector3.Zero();
  65119. }
  65120. SphericalPolynomial.prototype.addAmbient = function (color) {
  65121. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65122. this.xx = this.xx.add(colorVector);
  65123. this.yy = this.yy.add(colorVector);
  65124. this.zz = this.zz.add(colorVector);
  65125. };
  65126. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65127. var result = new SphericalPolynomial();
  65128. result.x = harmonics.L11.scale(1.02333);
  65129. result.y = harmonics.L1_1.scale(1.02333);
  65130. result.z = harmonics.L10.scale(1.02333);
  65131. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65132. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65133. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65134. result.yz = harmonics.L2_1.scale(0.858086);
  65135. result.zx = harmonics.L21.scale(0.858086);
  65136. result.xy = harmonics.L2_2.scale(0.858086);
  65137. result.scale(1.0 / Math.PI);
  65138. return result;
  65139. };
  65140. SphericalPolynomial.prototype.scale = function (scale) {
  65141. this.x = this.x.scale(scale);
  65142. this.y = this.y.scale(scale);
  65143. this.z = this.z.scale(scale);
  65144. this.xx = this.xx.scale(scale);
  65145. this.yy = this.yy.scale(scale);
  65146. this.zz = this.zz.scale(scale);
  65147. this.yz = this.yz.scale(scale);
  65148. this.zx = this.zx.scale(scale);
  65149. this.xy = this.xy.scale(scale);
  65150. };
  65151. return SphericalPolynomial;
  65152. }());
  65153. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65154. var SphericalHarmonics = /** @class */ (function () {
  65155. function SphericalHarmonics() {
  65156. this.L00 = BABYLON.Vector3.Zero();
  65157. this.L1_1 = BABYLON.Vector3.Zero();
  65158. this.L10 = BABYLON.Vector3.Zero();
  65159. this.L11 = BABYLON.Vector3.Zero();
  65160. this.L2_2 = BABYLON.Vector3.Zero();
  65161. this.L2_1 = BABYLON.Vector3.Zero();
  65162. this.L20 = BABYLON.Vector3.Zero();
  65163. this.L21 = BABYLON.Vector3.Zero();
  65164. this.L22 = BABYLON.Vector3.Zero();
  65165. }
  65166. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65167. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65168. var c = colorVector.scale(deltaSolidAngle);
  65169. this.L00 = this.L00.add(c.scale(0.282095));
  65170. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65171. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65172. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65173. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65174. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65175. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65176. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65177. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65178. };
  65179. SphericalHarmonics.prototype.scale = function (scale) {
  65180. this.L00 = this.L00.scale(scale);
  65181. this.L1_1 = this.L1_1.scale(scale);
  65182. this.L10 = this.L10.scale(scale);
  65183. this.L11 = this.L11.scale(scale);
  65184. this.L2_2 = this.L2_2.scale(scale);
  65185. this.L2_1 = this.L2_1.scale(scale);
  65186. this.L20 = this.L20.scale(scale);
  65187. this.L21 = this.L21.scale(scale);
  65188. this.L22 = this.L22.scale(scale);
  65189. };
  65190. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65191. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65192. //
  65193. // E_lm = A_l * L_lm
  65194. //
  65195. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65196. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65197. // the scaling factors are given in equation 9.
  65198. // Constant (Band 0)
  65199. this.L00 = this.L00.scale(3.141593);
  65200. // Linear (Band 1)
  65201. this.L1_1 = this.L1_1.scale(2.094395);
  65202. this.L10 = this.L10.scale(2.094395);
  65203. this.L11 = this.L11.scale(2.094395);
  65204. // Quadratic (Band 2)
  65205. this.L2_2 = this.L2_2.scale(0.785398);
  65206. this.L2_1 = this.L2_1.scale(0.785398);
  65207. this.L20 = this.L20.scale(0.785398);
  65208. this.L21 = this.L21.scale(0.785398);
  65209. this.L22 = this.L22.scale(0.785398);
  65210. };
  65211. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65212. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65213. // L = (1/pi) * E * rho
  65214. //
  65215. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65216. this.scale(1.0 / Math.PI);
  65217. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65218. // (The pixel shader must apply albedo after texture fetches, etc).
  65219. };
  65220. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65221. var result = new SphericalHarmonics();
  65222. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65223. result.L1_1 = polynomial.y.scale(0.977204);
  65224. result.L10 = polynomial.z.scale(0.977204);
  65225. result.L11 = polynomial.x.scale(0.977204);
  65226. result.L2_2 = polynomial.xy.scale(1.16538);
  65227. result.L2_1 = polynomial.yz.scale(1.16538);
  65228. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65229. result.L21 = polynomial.zx.scale(1.16538);
  65230. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65231. result.scale(Math.PI);
  65232. return result;
  65233. };
  65234. return SphericalHarmonics;
  65235. }());
  65236. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65237. })(BABYLON || (BABYLON = {}));
  65238. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65239. var BABYLON;
  65240. (function (BABYLON) {
  65241. var FileFaceOrientation = /** @class */ (function () {
  65242. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65243. this.name = name;
  65244. this.worldAxisForNormal = worldAxisForNormal;
  65245. this.worldAxisForFileX = worldAxisForFileX;
  65246. this.worldAxisForFileY = worldAxisForFileY;
  65247. }
  65248. return FileFaceOrientation;
  65249. }());
  65250. ;
  65251. /**
  65252. * Helper class dealing with the extraction of spherical polynomial dataArray
  65253. * from a cube map.
  65254. */
  65255. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65256. function CubeMapToSphericalPolynomialTools() {
  65257. }
  65258. /**
  65259. * Converts a texture to the according Spherical Polynomial data.
  65260. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65261. *
  65262. * @param texture The texture to extract the information from.
  65263. * @return The Spherical Polynomial data.
  65264. */
  65265. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65266. if (!texture.isCube) {
  65267. // Only supports cube Textures currently.
  65268. return null;
  65269. }
  65270. var size = texture.getSize().width;
  65271. var right = texture.readPixels(0);
  65272. var left = texture.readPixels(1);
  65273. var up;
  65274. var down;
  65275. if (texture.isRenderTarget) {
  65276. up = texture.readPixels(3);
  65277. down = texture.readPixels(2);
  65278. }
  65279. else {
  65280. up = texture.readPixels(2);
  65281. down = texture.readPixels(3);
  65282. }
  65283. var front = texture.readPixels(4);
  65284. var back = texture.readPixels(5);
  65285. var gammaSpace = texture.gammaSpace;
  65286. // Always read as RGBA.
  65287. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65288. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65289. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65290. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65291. }
  65292. var cubeInfo = {
  65293. size: size,
  65294. right: right,
  65295. left: left,
  65296. up: up,
  65297. down: down,
  65298. front: front,
  65299. back: back,
  65300. format: format,
  65301. type: type,
  65302. gammaSpace: gammaSpace,
  65303. };
  65304. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65305. };
  65306. /**
  65307. * Converts a cubemap to the according Spherical Polynomial data.
  65308. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65309. *
  65310. * @param cubeInfo The Cube map to extract the information from.
  65311. * @return The Spherical Polynomial data.
  65312. */
  65313. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65314. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65315. var totalSolidAngle = 0.0;
  65316. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65317. var du = 2.0 / cubeInfo.size;
  65318. var dv = du;
  65319. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65320. var minUV = du * 0.5 - 1.0;
  65321. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65322. var fileFace = this.FileFaces[faceIndex];
  65323. var dataArray = cubeInfo[fileFace.name];
  65324. var v = minUV;
  65325. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65326. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65327. // Because SP is still linear, so summation is fine in that basis.
  65328. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65329. for (var y = 0; y < cubeInfo.size; y++) {
  65330. var u = minUV;
  65331. for (var x = 0; x < cubeInfo.size; x++) {
  65332. // World direction (not normalised)
  65333. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65334. worldDirection.normalize();
  65335. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65336. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65337. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65338. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65339. // Handle Integer types.
  65340. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65341. r /= 255;
  65342. g /= 255;
  65343. b /= 255;
  65344. }
  65345. // Handle Gamma space textures.
  65346. if (cubeInfo.gammaSpace) {
  65347. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65348. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65349. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65350. }
  65351. var color = new BABYLON.Color3(r, g, b);
  65352. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65353. totalSolidAngle += deltaSolidAngle;
  65354. u += du;
  65355. }
  65356. v += dv;
  65357. }
  65358. }
  65359. // Solid angle for entire sphere is 4*pi
  65360. var sphereSolidAngle = 4.0 * Math.PI;
  65361. // Adjust the solid angle to allow for how many faces we processed.
  65362. var facesProcessed = 6.0;
  65363. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65364. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65365. // This is needed because the numerical integration over the cube uses a
  65366. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65367. // and also to compensate for accumulative error due to float precision in the summation.
  65368. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65369. sphericalHarmonics.scale(correctionFactor);
  65370. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65371. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65372. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65373. };
  65374. CubeMapToSphericalPolynomialTools.FileFaces = [
  65375. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65376. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65377. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65378. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65379. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65380. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65381. ];
  65382. return CubeMapToSphericalPolynomialTools;
  65383. }());
  65384. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65385. })(BABYLON || (BABYLON = {}));
  65386. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65387. var BABYLON;
  65388. (function (BABYLON) {
  65389. /**
  65390. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65391. */
  65392. var PanoramaToCubeMapTools = /** @class */ (function () {
  65393. function PanoramaToCubeMapTools() {
  65394. }
  65395. /**
  65396. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65397. *
  65398. * @param float32Array The source data.
  65399. * @param inputWidth The width of the input panorama.
  65400. * @param inputhHeight The height of the input panorama.
  65401. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65402. * @return The cubemap data
  65403. */
  65404. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65405. if (!float32Array) {
  65406. throw "ConvertPanoramaToCubemap: input cannot be null";
  65407. }
  65408. if (float32Array.length != inputWidth * inputHeight * 3) {
  65409. throw "ConvertPanoramaToCubemap: input size is wrong";
  65410. }
  65411. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65412. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65413. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65414. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65415. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65416. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65417. return {
  65418. front: textureFront,
  65419. back: textureBack,
  65420. left: textureLeft,
  65421. right: textureRight,
  65422. up: textureUp,
  65423. down: textureDown,
  65424. size: size,
  65425. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65426. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65427. gammaSpace: false,
  65428. };
  65429. };
  65430. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65431. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65432. var textureArray = new Float32Array(buffer);
  65433. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65434. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65435. var dy = 1 / texSize;
  65436. var fy = 0;
  65437. for (var y = 0; y < texSize; y++) {
  65438. var xv1 = faceData[0];
  65439. var xv2 = faceData[2];
  65440. for (var x = 0; x < texSize; x++) {
  65441. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65442. v.normalize();
  65443. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65444. // 3 channels per pixels
  65445. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65446. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65447. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65448. xv1 = xv1.add(rotDX1);
  65449. xv2 = xv2.add(rotDX2);
  65450. }
  65451. fy += dy;
  65452. }
  65453. return textureArray;
  65454. };
  65455. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65456. var theta = Math.atan2(vDir.z, vDir.x);
  65457. var phi = Math.acos(vDir.y);
  65458. while (theta < -Math.PI)
  65459. theta += 2 * Math.PI;
  65460. while (theta > Math.PI)
  65461. theta -= 2 * Math.PI;
  65462. var dx = theta / Math.PI;
  65463. var dy = phi / Math.PI;
  65464. // recenter.
  65465. dx = dx * 0.5 + 0.5;
  65466. var px = Math.round(dx * inputWidth);
  65467. if (px < 0)
  65468. px = 0;
  65469. else if (px >= inputWidth)
  65470. px = inputWidth - 1;
  65471. var py = Math.round(dy * inputHeight);
  65472. if (py < 0)
  65473. py = 0;
  65474. else if (py >= inputHeight)
  65475. py = inputHeight - 1;
  65476. var inputY = (inputHeight - py - 1);
  65477. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65478. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65479. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65480. return {
  65481. r: r,
  65482. g: g,
  65483. b: b
  65484. };
  65485. };
  65486. PanoramaToCubeMapTools.FACE_FRONT = [
  65487. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65488. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65489. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65490. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65491. ];
  65492. PanoramaToCubeMapTools.FACE_BACK = [
  65493. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65494. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65495. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65496. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65497. ];
  65498. PanoramaToCubeMapTools.FACE_RIGHT = [
  65499. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65500. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65501. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65502. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65503. ];
  65504. PanoramaToCubeMapTools.FACE_LEFT = [
  65505. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65506. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65507. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65508. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65509. ];
  65510. PanoramaToCubeMapTools.FACE_DOWN = [
  65511. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65512. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65513. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65514. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65515. ];
  65516. PanoramaToCubeMapTools.FACE_UP = [
  65517. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65518. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65519. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65520. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65521. ];
  65522. return PanoramaToCubeMapTools;
  65523. }());
  65524. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65525. })(BABYLON || (BABYLON = {}));
  65526. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65527. var BABYLON;
  65528. (function (BABYLON) {
  65529. ;
  65530. /**
  65531. * This groups tools to convert HDR texture to native colors array.
  65532. */
  65533. var HDRTools = /** @class */ (function () {
  65534. function HDRTools() {
  65535. }
  65536. HDRTools.Ldexp = function (mantissa, exponent) {
  65537. if (exponent > 1023) {
  65538. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65539. }
  65540. if (exponent < -1074) {
  65541. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65542. }
  65543. return mantissa * Math.pow(2, exponent);
  65544. };
  65545. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65546. if (exponent > 0) {
  65547. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65548. float32array[index + 0] = red * exponent;
  65549. float32array[index + 1] = green * exponent;
  65550. float32array[index + 2] = blue * exponent;
  65551. }
  65552. else {
  65553. float32array[index + 0] = 0;
  65554. float32array[index + 1] = 0;
  65555. float32array[index + 2] = 0;
  65556. }
  65557. };
  65558. HDRTools.readStringLine = function (uint8array, startIndex) {
  65559. var line = "";
  65560. var character = "";
  65561. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65562. character = String.fromCharCode(uint8array[i]);
  65563. if (character == "\n") {
  65564. break;
  65565. }
  65566. line += character;
  65567. }
  65568. return line;
  65569. };
  65570. /**
  65571. * Reads header information from an RGBE texture stored in a native array.
  65572. * More information on this format are available here:
  65573. * https://en.wikipedia.org/wiki/RGBE_image_format
  65574. *
  65575. * @param uint8array The binary file stored in native array.
  65576. * @return The header information.
  65577. */
  65578. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65579. var height = 0;
  65580. var width = 0;
  65581. var line = this.readStringLine(uint8array, 0);
  65582. if (line[0] != '#' || line[1] != '?') {
  65583. throw "Bad HDR Format.";
  65584. }
  65585. var endOfHeader = false;
  65586. var findFormat = false;
  65587. var lineIndex = 0;
  65588. do {
  65589. lineIndex += (line.length + 1);
  65590. line = this.readStringLine(uint8array, lineIndex);
  65591. if (line == "FORMAT=32-bit_rle_rgbe") {
  65592. findFormat = true;
  65593. }
  65594. else if (line.length == 0) {
  65595. endOfHeader = true;
  65596. }
  65597. } while (!endOfHeader);
  65598. if (!findFormat) {
  65599. throw "HDR Bad header format, unsupported FORMAT";
  65600. }
  65601. lineIndex += (line.length + 1);
  65602. line = this.readStringLine(uint8array, lineIndex);
  65603. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65604. var match = sizeRegexp.exec(line);
  65605. // TODO. Support +Y and -X if needed.
  65606. if (!match || match.length < 3) {
  65607. throw "HDR Bad header format, no size";
  65608. }
  65609. width = parseInt(match[2]);
  65610. height = parseInt(match[1]);
  65611. if (width < 8 || width > 0x7fff) {
  65612. throw "HDR Bad header format, unsupported size";
  65613. }
  65614. lineIndex += (line.length + 1);
  65615. return {
  65616. height: height,
  65617. width: width,
  65618. dataPosition: lineIndex
  65619. };
  65620. };
  65621. /**
  65622. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65623. * This RGBE texture needs to store the information as a panorama.
  65624. *
  65625. * More information on this format are available here:
  65626. * https://en.wikipedia.org/wiki/RGBE_image_format
  65627. *
  65628. * @param buffer The binary file stored in an array buffer.
  65629. * @param size The expected size of the extracted cubemap.
  65630. * @return The Cube Map information.
  65631. */
  65632. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65633. var uint8array = new Uint8Array(buffer);
  65634. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65635. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65636. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65637. return cubeMapData;
  65638. };
  65639. /**
  65640. * Returns the pixels data extracted from an RGBE texture.
  65641. * This pixels will be stored left to right up to down in the R G B order in one array.
  65642. *
  65643. * More information on this format are available here:
  65644. * https://en.wikipedia.org/wiki/RGBE_image_format
  65645. *
  65646. * @param uint8array The binary file stored in an array buffer.
  65647. * @param hdrInfo The header information of the file.
  65648. * @return The pixels data in RGB right to left up to down order.
  65649. */
  65650. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65651. // Keep for multi format supports.
  65652. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65653. };
  65654. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65655. var num_scanlines = hdrInfo.height;
  65656. var scanline_width = hdrInfo.width;
  65657. var a, b, c, d, count;
  65658. var dataIndex = hdrInfo.dataPosition;
  65659. var index = 0, endIndex = 0, i = 0;
  65660. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65661. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65662. // 3 channels of 4 bytes per pixel in float.
  65663. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65664. var resultArray = new Float32Array(resultBuffer);
  65665. // read in each successive scanline
  65666. while (num_scanlines > 0) {
  65667. a = uint8array[dataIndex++];
  65668. b = uint8array[dataIndex++];
  65669. c = uint8array[dataIndex++];
  65670. d = uint8array[dataIndex++];
  65671. if (a != 2 || b != 2 || (c & 0x80)) {
  65672. // this file is not run length encoded
  65673. throw "HDR Bad header format, not RLE";
  65674. }
  65675. if (((c << 8) | d) != scanline_width) {
  65676. throw "HDR Bad header format, wrong scan line width";
  65677. }
  65678. index = 0;
  65679. // read each of the four channels for the scanline into the buffer
  65680. for (i = 0; i < 4; i++) {
  65681. endIndex = (i + 1) * scanline_width;
  65682. while (index < endIndex) {
  65683. a = uint8array[dataIndex++];
  65684. b = uint8array[dataIndex++];
  65685. if (a > 128) {
  65686. // a run of the same value
  65687. count = a - 128;
  65688. if ((count == 0) || (count > endIndex - index)) {
  65689. throw "HDR Bad Format, bad scanline data (run)";
  65690. }
  65691. while (count-- > 0) {
  65692. scanLineArray[index++] = b;
  65693. }
  65694. }
  65695. else {
  65696. // a non-run
  65697. count = a;
  65698. if ((count == 0) || (count > endIndex - index)) {
  65699. throw "HDR Bad Format, bad scanline data (non-run)";
  65700. }
  65701. scanLineArray[index++] = b;
  65702. if (--count > 0) {
  65703. for (var j = 0; j < count; j++) {
  65704. scanLineArray[index++] = uint8array[dataIndex++];
  65705. }
  65706. }
  65707. }
  65708. }
  65709. }
  65710. // now convert data from buffer into floats
  65711. for (i = 0; i < scanline_width; i++) {
  65712. a = scanLineArray[i];
  65713. b = scanLineArray[i + scanline_width];
  65714. c = scanLineArray[i + 2 * scanline_width];
  65715. d = scanLineArray[i + 3 * scanline_width];
  65716. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65717. }
  65718. num_scanlines--;
  65719. }
  65720. return resultArray;
  65721. };
  65722. return HDRTools;
  65723. }());
  65724. BABYLON.HDRTools = HDRTools;
  65725. })(BABYLON || (BABYLON = {}));
  65726. //# sourceMappingURL=babylon.hdr.js.map
  65727. var BABYLON;
  65728. (function (BABYLON) {
  65729. /**
  65730. * This represents a texture coming from an HDR input.
  65731. *
  65732. * The only supported format is currently panorama picture stored in RGBE format.
  65733. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65734. */
  65735. var HDRCubeTexture = /** @class */ (function (_super) {
  65736. __extends(HDRCubeTexture, _super);
  65737. /**
  65738. * Instantiates an HDRTexture from the following parameters.
  65739. *
  65740. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65741. * @param scene The scene the texture will be used in
  65742. * @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.
  65743. * @param noMipmap Forces to not generate the mipmap if true
  65744. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  65745. * @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)
  65746. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65747. */
  65748. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65749. if (noMipmap === void 0) { noMipmap = false; }
  65750. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65751. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65752. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65753. if (onLoad === void 0) { onLoad = null; }
  65754. if (onError === void 0) { onError = null; }
  65755. var _this = _super.call(this, scene) || this;
  65756. _this._useInGammaSpace = false;
  65757. _this._generateHarmonics = true;
  65758. _this._isBABYLONPreprocessed = false;
  65759. _this._onLoad = null;
  65760. _this._onError = null;
  65761. /**
  65762. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65763. */
  65764. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65765. /**
  65766. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65767. * This is usefull at run time to apply the good shader.
  65768. */
  65769. _this.isPMREM = false;
  65770. _this._isBlocking = true;
  65771. if (!url) {
  65772. return _this;
  65773. }
  65774. _this.name = url;
  65775. _this.url = url;
  65776. _this.hasAlpha = false;
  65777. _this.isCube = true;
  65778. _this._textureMatrix = BABYLON.Matrix.Identity();
  65779. _this._onLoad = onLoad;
  65780. _this._onError = onError;
  65781. _this.gammaSpace = false;
  65782. var caps = scene.getEngine().getCaps();
  65783. if (size) {
  65784. _this._isBABYLONPreprocessed = false;
  65785. _this._noMipmap = noMipmap;
  65786. _this._size = size;
  65787. _this._useInGammaSpace = useInGammaSpace;
  65788. _this._usePMREMGenerator = usePMREMGenerator &&
  65789. caps.textureLOD &&
  65790. caps.textureFloat &&
  65791. !_this._useInGammaSpace;
  65792. }
  65793. else {
  65794. _this._isBABYLONPreprocessed = true;
  65795. _this._noMipmap = false;
  65796. _this._useInGammaSpace = false;
  65797. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65798. !_this._useInGammaSpace;
  65799. }
  65800. _this.isPMREM = _this._usePMREMGenerator;
  65801. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65802. if (!_this._texture) {
  65803. if (!scene.useDelayedTextureLoading) {
  65804. _this.loadTexture();
  65805. }
  65806. else {
  65807. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65808. }
  65809. }
  65810. return _this;
  65811. }
  65812. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65813. /**
  65814. * Gets wether or not the texture is blocking during loading.
  65815. */
  65816. get: function () {
  65817. return this._isBlocking;
  65818. },
  65819. /**
  65820. * Sets wether or not the texture is blocking during loading.
  65821. */
  65822. set: function (value) {
  65823. this._isBlocking = value;
  65824. },
  65825. enumerable: true,
  65826. configurable: true
  65827. });
  65828. /**
  65829. * Occurs when the file is a preprocessed .babylon.hdr file.
  65830. */
  65831. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65832. var _this = this;
  65833. var mipLevels = 0;
  65834. var floatArrayView = null;
  65835. var scene = this.getScene();
  65836. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65837. var mips = new Array();
  65838. if (!floatArrayView) {
  65839. return mips;
  65840. }
  65841. var startIndex = 30;
  65842. for (var level = 0; level < mipLevels; level++) {
  65843. mips.push([]);
  65844. // Fill each pixel of the mip level.
  65845. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65847. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65848. mips[level].push(faceData);
  65849. startIndex += faceSize;
  65850. }
  65851. }
  65852. return mips;
  65853. } : null;
  65854. var callback = function (buffer) {
  65855. var scene = _this.getScene();
  65856. if (!scene) {
  65857. return null;
  65858. }
  65859. // Create Native Array Views
  65860. var intArrayView = new Int32Array(buffer);
  65861. floatArrayView = new Float32Array(buffer);
  65862. // Fill header.
  65863. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65864. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65865. // Update Texture Information.
  65866. if (!_this._texture) {
  65867. return null;
  65868. }
  65869. _this._texture.updateSize(_this._size, _this._size);
  65870. // Fill polynomial information.
  65871. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65872. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65873. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65874. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65875. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65876. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65877. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65878. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65879. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65880. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65881. _this.sphericalPolynomial = sphericalPolynomial;
  65882. // Fill pixel data.
  65883. mipLevels = intArrayView[29]; // Number of mip levels.
  65884. var startIndex = 30;
  65885. var data = [];
  65886. var faceSize = Math.pow(_this._size, 2) * 3;
  65887. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65888. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65889. startIndex += faceSize;
  65890. }
  65891. var results = [];
  65892. var byteArray = null;
  65893. // Push each faces.
  65894. for (var k = 0; k < 6; k++) {
  65895. var dataFace = null;
  65896. // To be deprecated.
  65897. if (version === 1) {
  65898. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65899. dataFace = data[j];
  65900. }
  65901. // If special cases.
  65902. if (!mipmapGenerator && dataFace) {
  65903. if (!scene.getEngine().getCaps().textureFloat) {
  65904. // 3 channels of 1 bytes per pixel in bytes.
  65905. var byteBuffer = new ArrayBuffer(faceSize);
  65906. byteArray = new Uint8Array(byteBuffer);
  65907. }
  65908. for (var i = 0; i < _this._size * _this._size; i++) {
  65909. // Put in gamma space if requested.
  65910. if (_this._useInGammaSpace) {
  65911. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65912. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65913. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65914. }
  65915. // Convert to int texture for fallback.
  65916. if (byteArray) {
  65917. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65918. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65919. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65920. // May use luminance instead if the result is not accurate.
  65921. var max = Math.max(Math.max(r, g), b);
  65922. if (max > 255) {
  65923. var scale = 255 / max;
  65924. r *= scale;
  65925. g *= scale;
  65926. b *= scale;
  65927. }
  65928. byteArray[(i * 3) + 0] = r;
  65929. byteArray[(i * 3) + 1] = g;
  65930. byteArray[(i * 3) + 2] = b;
  65931. }
  65932. }
  65933. }
  65934. // Fill the array accordingly.
  65935. if (byteArray) {
  65936. results.push(byteArray);
  65937. }
  65938. else {
  65939. results.push(dataFace);
  65940. }
  65941. }
  65942. return results;
  65943. };
  65944. if (scene) {
  65945. 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);
  65946. }
  65947. };
  65948. /**
  65949. * Occurs when the file is raw .hdr file.
  65950. */
  65951. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65952. var _this = this;
  65953. var callback = function (buffer) {
  65954. var scene = _this.getScene();
  65955. if (!scene) {
  65956. return null;
  65957. }
  65958. // Extract the raw linear data.
  65959. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65960. // Generate harmonics if needed.
  65961. if (_this._generateHarmonics) {
  65962. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65963. _this.sphericalPolynomial = sphericalPolynomial;
  65964. }
  65965. var results = [];
  65966. var byteArray = null;
  65967. // Push each faces.
  65968. for (var j = 0; j < 6; j++) {
  65969. // Create uintarray fallback.
  65970. if (!scene.getEngine().getCaps().textureFloat) {
  65971. // 3 channels of 1 bytes per pixel in bytes.
  65972. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65973. byteArray = new Uint8Array(byteBuffer);
  65974. }
  65975. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65976. // If special cases.
  65977. if (_this._useInGammaSpace || byteArray) {
  65978. for (var i = 0; i < _this._size * _this._size; i++) {
  65979. // Put in gamma space if requested.
  65980. if (_this._useInGammaSpace) {
  65981. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65982. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65983. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65984. }
  65985. // Convert to int texture for fallback.
  65986. if (byteArray) {
  65987. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65988. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65989. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65990. // May use luminance instead if the result is not accurate.
  65991. var max = Math.max(Math.max(r, g), b);
  65992. if (max > 255) {
  65993. var scale = 255 / max;
  65994. r *= scale;
  65995. g *= scale;
  65996. b *= scale;
  65997. }
  65998. byteArray[(i * 3) + 0] = r;
  65999. byteArray[(i * 3) + 1] = g;
  66000. byteArray[(i * 3) + 2] = b;
  66001. }
  66002. }
  66003. }
  66004. if (byteArray) {
  66005. results.push(byteArray);
  66006. }
  66007. else {
  66008. results.push(dataFace);
  66009. }
  66010. }
  66011. return results;
  66012. };
  66013. var mipmapGenerator = null;
  66014. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66015. // if (!this._noMipmap &&
  66016. // this._usePMREMGenerator) {
  66017. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66018. // // Custom setup of the generator matching with the PBR shader values.
  66019. // var generator = new BABYLON.PMREMGenerator(data,
  66020. // this._size,
  66021. // this._size,
  66022. // 0,
  66023. // 3,
  66024. // this.getScene().getEngine().getCaps().textureFloat,
  66025. // 2048,
  66026. // 0.25,
  66027. // false,
  66028. // true);
  66029. // return generator.filterCubeMap();
  66030. // };
  66031. // }
  66032. var scene = this.getScene();
  66033. if (scene) {
  66034. 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);
  66035. }
  66036. };
  66037. /**
  66038. * Starts the loading process of the texture.
  66039. */
  66040. HDRCubeTexture.prototype.loadTexture = function () {
  66041. if (this._isBABYLONPreprocessed) {
  66042. this.loadBabylonTexture();
  66043. }
  66044. else {
  66045. this.loadHDRTexture();
  66046. }
  66047. };
  66048. HDRCubeTexture.prototype.clone = function () {
  66049. var scene = this.getScene();
  66050. if (!scene) {
  66051. return this;
  66052. }
  66053. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66054. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66055. // Base texture
  66056. newTexture.level = this.level;
  66057. newTexture.wrapU = this.wrapU;
  66058. newTexture.wrapV = this.wrapV;
  66059. newTexture.coordinatesIndex = this.coordinatesIndex;
  66060. newTexture.coordinatesMode = this.coordinatesMode;
  66061. return newTexture;
  66062. };
  66063. // Methods
  66064. HDRCubeTexture.prototype.delayLoad = function () {
  66065. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66066. return;
  66067. }
  66068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66069. this._texture = this._getFromCache(this.url, this._noMipmap);
  66070. if (!this._texture) {
  66071. this.loadTexture();
  66072. }
  66073. };
  66074. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66075. return this._textureMatrix;
  66076. };
  66077. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66078. this._textureMatrix = value;
  66079. };
  66080. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66081. var texture = null;
  66082. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66083. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66084. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66085. texture.name = parsedTexture.name;
  66086. texture.hasAlpha = parsedTexture.hasAlpha;
  66087. texture.level = parsedTexture.level;
  66088. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66089. texture.isBlocking = parsedTexture.isBlocking;
  66090. }
  66091. return texture;
  66092. };
  66093. HDRCubeTexture.prototype.serialize = function () {
  66094. if (!this.name) {
  66095. return null;
  66096. }
  66097. var serializationObject = {};
  66098. serializationObject.name = this.name;
  66099. serializationObject.hasAlpha = this.hasAlpha;
  66100. serializationObject.isCube = true;
  66101. serializationObject.level = this.level;
  66102. serializationObject.size = this._size;
  66103. serializationObject.coordinatesMode = this.coordinatesMode;
  66104. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66105. serializationObject.generateHarmonics = this._generateHarmonics;
  66106. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66107. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66108. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66109. serializationObject.noMipmap = this._noMipmap;
  66110. serializationObject.isBlocking = this._isBlocking;
  66111. return serializationObject;
  66112. };
  66113. /**
  66114. * Saves as a file the data contained in the texture in a binary format.
  66115. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66116. * as the spherical used in the lighting.
  66117. * @param url The HDR file url.
  66118. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66119. * @param onError Method called if any error happens during download.
  66120. * @return The packed binary data.
  66121. */
  66122. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66123. if (onError === void 0) { onError = null; }
  66124. var callback = function (buffer) {
  66125. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66126. // Returns a URL you can use as a href.
  66127. var objUrl = window.URL.createObjectURL(data);
  66128. // Simulates a link to it and click to dowload.
  66129. var a = document.createElement("a");
  66130. document.body.appendChild(a);
  66131. a.style.display = "none";
  66132. a.href = objUrl;
  66133. a.download = "envmap.babylon.hdr";
  66134. a.click();
  66135. };
  66136. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66137. };
  66138. /**
  66139. * Serializes the data contained in the texture in a binary format.
  66140. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66141. * as the spherical used in the lighting.
  66142. * @param url The HDR file url.
  66143. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66144. * @param onError Method called if any error happens during download.
  66145. * @return The packed binary data.
  66146. */
  66147. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66148. if (onError === void 0) { onError = null; }
  66149. // Needs the url tho create the texture.
  66150. if (!url) {
  66151. return;
  66152. }
  66153. // Check Power of two size.
  66154. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66155. return;
  66156. }
  66157. // Coming Back in 3.x.
  66158. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66159. };
  66160. HDRCubeTexture._facesMapping = [
  66161. "right",
  66162. "left",
  66163. "up",
  66164. "down",
  66165. "front",
  66166. "back"
  66167. ];
  66168. return HDRCubeTexture;
  66169. }(BABYLON.BaseTexture));
  66170. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66171. })(BABYLON || (BABYLON = {}));
  66172. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66173. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66174. // Huge respect for a such great lib.
  66175. // Earcut license:
  66176. // Copyright (c) 2016, Mapbox
  66177. //
  66178. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66179. // with or without fee is hereby granted, provided that the above copyright notice
  66180. // and this permission notice appear in all copies.
  66181. //
  66182. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66183. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66184. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66185. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66186. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66187. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66188. // THIS SOFTWARE.
  66189. var Earcut;
  66190. (function (Earcut) {
  66191. /**
  66192. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66193. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66194. * @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).
  66195. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66196. */
  66197. function earcut(data, holeIndices, dim) {
  66198. dim = dim || 2;
  66199. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66200. if (!outerNode)
  66201. return triangles;
  66202. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66203. if (hasHoles)
  66204. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66205. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66206. if (data.length > 80 * dim) {
  66207. minX = maxX = data[0];
  66208. minY = maxY = data[1];
  66209. for (var i = dim; i < outerLen; i += dim) {
  66210. x = data[i];
  66211. y = data[i + 1];
  66212. if (x < minX)
  66213. minX = x;
  66214. if (y < minY)
  66215. minY = y;
  66216. if (x > maxX)
  66217. maxX = x;
  66218. if (y > maxY)
  66219. maxY = y;
  66220. }
  66221. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66222. size = Math.max(maxX - minX, maxY - minY);
  66223. }
  66224. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66225. return triangles;
  66226. }
  66227. Earcut.earcut = earcut;
  66228. var Node = /** @class */ (function () {
  66229. function Node(i, x, y) {
  66230. this.i = i;
  66231. this.x = x;
  66232. this.y = y;
  66233. this.prev = null;
  66234. this.next = null;
  66235. this.z = null;
  66236. this.prevZ = null;
  66237. this.nextZ = null;
  66238. this.steiner = false;
  66239. }
  66240. return Node;
  66241. }());
  66242. // create a circular doubly linked list from polygon points in the specified winding order
  66243. function linkedList(data, start, end, dim, clockwise) {
  66244. var i, last = null;
  66245. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66246. for (i = start; i < end; i += dim)
  66247. last = insertNode(i, data[i], data[i + 1], last);
  66248. }
  66249. else {
  66250. for (i = end - dim; i >= start; i -= dim)
  66251. last = insertNode(i, data[i], data[i + 1], last);
  66252. }
  66253. if (last && equals(last, last.next)) {
  66254. removeNode(last);
  66255. last = last.next;
  66256. }
  66257. return last;
  66258. }
  66259. // eliminate colinear or duplicate points
  66260. function filterPoints(start, end) {
  66261. if (!start)
  66262. return start;
  66263. if (!end)
  66264. end = start;
  66265. var p = start, again;
  66266. do {
  66267. again = false;
  66268. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66269. removeNode(p);
  66270. p = end = p.prev;
  66271. if (p === p.next)
  66272. return undefined;
  66273. again = true;
  66274. }
  66275. else {
  66276. p = p.next;
  66277. }
  66278. } while (again || p !== end);
  66279. return end;
  66280. }
  66281. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66282. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66283. if (!ear)
  66284. return;
  66285. // interlink polygon nodes in z-order
  66286. if (!pass && size)
  66287. indexCurve(ear, minX, minY, size);
  66288. var stop = ear, prev, next;
  66289. // iterate through ears, slicing them one by one
  66290. while (ear.prev !== ear.next) {
  66291. prev = ear.prev;
  66292. next = ear.next;
  66293. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66294. // cut off the triangle
  66295. triangles.push(prev.i / dim);
  66296. triangles.push(ear.i / dim);
  66297. triangles.push(next.i / dim);
  66298. removeNode(ear);
  66299. // skipping the next vertice leads to less sliver triangles
  66300. ear = next.next;
  66301. stop = next.next;
  66302. continue;
  66303. }
  66304. ear = next;
  66305. // if we looped through the whole remaining polygon and can't find any more ears
  66306. if (ear === stop) {
  66307. // try filtering points and slicing again
  66308. if (!pass) {
  66309. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66310. // if this didn't work, try curing all small self-intersections locally
  66311. }
  66312. else if (pass === 1) {
  66313. ear = cureLocalIntersections(ear, triangles, dim);
  66314. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66315. // as a last resort, try splitting the remaining polygon into two
  66316. }
  66317. else if (pass === 2) {
  66318. splitEarcut(ear, triangles, dim, minX, minY, size);
  66319. }
  66320. break;
  66321. }
  66322. }
  66323. }
  66324. // check whether a polygon node forms a valid ear with adjacent nodes
  66325. function isEar(ear) {
  66326. var a = ear.prev, b = ear, c = ear.next;
  66327. if (area(a, b, c) >= 0)
  66328. return false; // reflex, can't be an ear
  66329. // now make sure we don't have other points inside the potential ear
  66330. var p = ear.next.next;
  66331. while (p !== ear.prev) {
  66332. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66333. area(p.prev, p, p.next) >= 0)
  66334. return false;
  66335. p = p.next;
  66336. }
  66337. return true;
  66338. }
  66339. function isEarHashed(ear, minX, minY, size) {
  66340. var a = ear.prev, b = ear, c = ear.next;
  66341. if (area(a, b, c) >= 0)
  66342. return false; // reflex, can't be an ear
  66343. // triangle bbox; min & max are calculated like this for speed
  66344. 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);
  66345. // z-order range for the current triangle bbox;
  66346. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66347. // first look for points inside the triangle in increasing z-order
  66348. var p = ear.nextZ;
  66349. while (p && p.z <= maxZ) {
  66350. if (p !== ear.prev &&
  66351. p !== ear.next &&
  66352. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66353. area(p.prev, p, p.next) >= 0)
  66354. return false;
  66355. p = p.nextZ;
  66356. }
  66357. // then look for points in decreasing z-order
  66358. p = ear.prevZ;
  66359. while (p && p.z >= minZ) {
  66360. if (p !== ear.prev &&
  66361. p !== ear.next &&
  66362. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66363. area(p.prev, p, p.next) >= 0)
  66364. return false;
  66365. p = p.prevZ;
  66366. }
  66367. return true;
  66368. }
  66369. // go through all polygon nodes and cure small local self-intersections
  66370. function cureLocalIntersections(start, triangles, dim) {
  66371. var p = start;
  66372. do {
  66373. var a = p.prev, b = p.next.next;
  66374. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66375. triangles.push(a.i / dim);
  66376. triangles.push(p.i / dim);
  66377. triangles.push(b.i / dim);
  66378. // remove two nodes involved
  66379. removeNode(p);
  66380. removeNode(p.next);
  66381. p = start = b;
  66382. }
  66383. p = p.next;
  66384. } while (p !== start);
  66385. return p;
  66386. }
  66387. // try splitting polygon into two and triangulate them independently
  66388. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66389. // look for a valid diagonal that divides the polygon into two
  66390. var a = start;
  66391. do {
  66392. var b = a.next.next;
  66393. while (b !== a.prev) {
  66394. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66395. // split the polygon in two by the diagonal
  66396. var c = splitPolygon(a, b);
  66397. // filter colinear points around the cuts
  66398. a = filterPoints(a, a.next);
  66399. c = filterPoints(c, c.next);
  66400. // run earcut on each half
  66401. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66402. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66403. return;
  66404. }
  66405. b = b.next;
  66406. }
  66407. a = a.next;
  66408. } while (a !== start);
  66409. }
  66410. // link every hole into the outer loop, producing a single-ring polygon without holes
  66411. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66412. var queue = [], i, len, start, end, list;
  66413. for (i = 0, len = holeIndices.length; i < len; i++) {
  66414. start = holeIndices[i] * dim;
  66415. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66416. list = linkedList(data, start, end, dim, false);
  66417. if (list === list.next)
  66418. list.steiner = true;
  66419. queue.push(getLeftmost(list));
  66420. }
  66421. queue.sort(compareX);
  66422. // process holes from left to right
  66423. for (i = 0; i < queue.length; i++) {
  66424. eliminateHole(queue[i], outerNode);
  66425. outerNode = filterPoints(outerNode, outerNode.next);
  66426. }
  66427. return outerNode;
  66428. }
  66429. function compareX(a, b) {
  66430. return a.x - b.x;
  66431. }
  66432. // find a bridge between vertices that connects hole with an outer ring and and link it
  66433. function eliminateHole(hole, outerNode) {
  66434. outerNode = findHoleBridge(hole, outerNode);
  66435. if (outerNode) {
  66436. var b = splitPolygon(outerNode, hole);
  66437. filterPoints(b, b.next);
  66438. }
  66439. }
  66440. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66441. function findHoleBridge(hole, outerNode) {
  66442. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66443. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66444. // segment's endpoint with lesser x will be potential connection point
  66445. do {
  66446. if (hy <= p.y && hy >= p.next.y) {
  66447. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66448. if (x <= hx && x > qx) {
  66449. qx = x;
  66450. if (x === hx) {
  66451. if (hy === p.y)
  66452. return p;
  66453. if (hy === p.next.y)
  66454. return p.next;
  66455. }
  66456. m = p.x < p.next.x ? p : p.next;
  66457. }
  66458. }
  66459. p = p.next;
  66460. } while (p !== outerNode);
  66461. if (!m)
  66462. return null;
  66463. if (hx === qx)
  66464. return m.prev; // hole touches outer segment; pick lower endpoint
  66465. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66466. // if there are no points found, we have a valid connection;
  66467. // otherwise choose the point of the minimum angle with the ray as connection point
  66468. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66469. p = m.next;
  66470. while (p !== stop) {
  66471. if (hx >= p.x &&
  66472. p.x >= mx &&
  66473. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66474. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66475. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66476. m = p;
  66477. tanMin = tan;
  66478. }
  66479. }
  66480. p = p.next;
  66481. }
  66482. return m;
  66483. }
  66484. // interlink polygon nodes in z-order
  66485. function indexCurve(start, minX, minY, size) {
  66486. var p = start;
  66487. do {
  66488. if (p.z === null)
  66489. p.z = zOrder(p.x, p.y, minX, minY, size);
  66490. p.prevZ = p.prev;
  66491. p.nextZ = p.next;
  66492. p = p.next;
  66493. } while (p !== start);
  66494. p.prevZ.nextZ = null;
  66495. p.prevZ = null;
  66496. sortLinked(p);
  66497. }
  66498. // Simon Tatham's linked list merge sort algorithm
  66499. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66500. function sortLinked(list) {
  66501. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66502. do {
  66503. p = list;
  66504. list = null;
  66505. tail = null;
  66506. numMerges = 0;
  66507. while (p) {
  66508. numMerges++;
  66509. q = p;
  66510. pSize = 0;
  66511. for (i = 0; i < inSize; i++) {
  66512. pSize++;
  66513. q = q.nextZ;
  66514. if (!q)
  66515. break;
  66516. }
  66517. qSize = inSize;
  66518. while (pSize > 0 || (qSize > 0 && q)) {
  66519. if (pSize === 0) {
  66520. e = q;
  66521. q = q.nextZ;
  66522. qSize--;
  66523. }
  66524. else if (qSize === 0 || !q) {
  66525. e = p;
  66526. p = p.nextZ;
  66527. pSize--;
  66528. }
  66529. else if (p.z <= q.z) {
  66530. e = p;
  66531. p = p.nextZ;
  66532. pSize--;
  66533. }
  66534. else {
  66535. e = q;
  66536. q = q.nextZ;
  66537. qSize--;
  66538. }
  66539. if (tail)
  66540. tail.nextZ = e;
  66541. else
  66542. list = e;
  66543. e.prevZ = tail;
  66544. tail = e;
  66545. }
  66546. p = q;
  66547. }
  66548. tail.nextZ = null;
  66549. inSize *= 2;
  66550. } while (numMerges > 1);
  66551. return list;
  66552. }
  66553. // z-order of a point given coords and size of the data bounding box
  66554. function zOrder(x, y, minX, minY, size) {
  66555. // coords are transformed into non-negative 15-bit integer range
  66556. x = 32767 * (x - minX) / size;
  66557. y = 32767 * (y - minY) / size;
  66558. x = (x | (x << 8)) & 0x00FF00FF;
  66559. x = (x | (x << 4)) & 0x0F0F0F0F;
  66560. x = (x | (x << 2)) & 0x33333333;
  66561. x = (x | (x << 1)) & 0x55555555;
  66562. y = (y | (y << 8)) & 0x00FF00FF;
  66563. y = (y | (y << 4)) & 0x0F0F0F0F;
  66564. y = (y | (y << 2)) & 0x33333333;
  66565. y = (y | (y << 1)) & 0x55555555;
  66566. return x | (y << 1);
  66567. }
  66568. // find the leftmost node of a polygon ring
  66569. function getLeftmost(start) {
  66570. var p = start, leftmost = start;
  66571. do {
  66572. if (p.x < leftmost.x)
  66573. leftmost = p;
  66574. p = p.next;
  66575. } while (p !== start);
  66576. return leftmost;
  66577. }
  66578. // check if a point lies within a convex triangle
  66579. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66580. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66581. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66582. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66583. }
  66584. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66585. function isValidDiagonal(a, b) {
  66586. return a.next.i !== b.i &&
  66587. a.prev.i !== b.i &&
  66588. !intersectsPolygon(a, b) &&
  66589. locallyInside(a, b) &&
  66590. locallyInside(b, a) &&
  66591. middleInside(a, b);
  66592. }
  66593. // signed area of a triangle
  66594. function area(p, q, r) {
  66595. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66596. }
  66597. // check if two points are equal
  66598. function equals(p1, p2) {
  66599. return p1.x === p2.x && p1.y === p2.y;
  66600. }
  66601. // check if two segments intersect
  66602. function intersects(p1, q1, p2, q2) {
  66603. if ((equals(p1, q1) && equals(p2, q2)) ||
  66604. (equals(p1, q2) && equals(p2, q1)))
  66605. return true;
  66606. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66607. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66608. }
  66609. // check if a polygon diagonal intersects any polygon segments
  66610. function intersectsPolygon(a, b) {
  66611. var p = a;
  66612. do {
  66613. if (p.i !== a.i &&
  66614. p.next.i !== a.i &&
  66615. p.i !== b.i &&
  66616. p.next.i !== b.i &&
  66617. intersects(p, p.next, a, b))
  66618. return true;
  66619. p = p.next;
  66620. } while (p !== a);
  66621. return false;
  66622. }
  66623. // check if a polygon diagonal is locally inside the polygon
  66624. function locallyInside(a, b) {
  66625. return area(a.prev, a, a.next) < 0
  66626. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66627. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66628. }
  66629. // check if the middle point of a polygon diagonal is inside the polygon
  66630. function middleInside(a, b) {
  66631. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66632. do {
  66633. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66634. inside = !inside;
  66635. p = p.next;
  66636. } while (p !== a);
  66637. return inside;
  66638. }
  66639. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66640. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66641. function splitPolygon(a, b) {
  66642. 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;
  66643. a.next = b;
  66644. b.prev = a;
  66645. a2.next = an;
  66646. an.prev = a2;
  66647. b2.next = a2;
  66648. a2.prev = b2;
  66649. bp.next = b2;
  66650. b2.prev = bp;
  66651. return b2;
  66652. }
  66653. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66654. function insertNode(i, x, y, last) {
  66655. var p = new Node(i, x, y);
  66656. if (!last) {
  66657. p.prev = p;
  66658. p.next = p;
  66659. }
  66660. else {
  66661. p.next = last.next;
  66662. p.prev = last;
  66663. last.next.prev = p;
  66664. last.next = p;
  66665. }
  66666. return p;
  66667. }
  66668. function removeNode(p) {
  66669. p.next.prev = p.prev;
  66670. p.prev.next = p.next;
  66671. if (p.prevZ)
  66672. p.prevZ.nextZ = p.nextZ;
  66673. if (p.nextZ)
  66674. p.nextZ.prevZ = p.prevZ;
  66675. }
  66676. /**
  66677. * return a percentage difference between the polygon area and its triangulation area;
  66678. * used to verify correctness of triangulation
  66679. */
  66680. function deviation(data, holeIndices, dim, triangles) {
  66681. var hasHoles = holeIndices && holeIndices.length;
  66682. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66683. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66684. if (hasHoles) {
  66685. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66686. var start = holeIndices[i] * dim;
  66687. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66688. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66689. }
  66690. }
  66691. var trianglesArea = 0;
  66692. for (i = 0; i < triangles.length; i += 3) {
  66693. var a = triangles[i] * dim;
  66694. var b = triangles[i + 1] * dim;
  66695. var c = triangles[i + 2] * dim;
  66696. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66697. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66698. }
  66699. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66700. }
  66701. Earcut.deviation = deviation;
  66702. ;
  66703. function signedArea(data, start, end, dim) {
  66704. var sum = 0;
  66705. for (var i = start, j = end - dim; i < end; i += dim) {
  66706. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66707. j = i;
  66708. }
  66709. return sum;
  66710. }
  66711. /**
  66712. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66713. */
  66714. function flatten(data) {
  66715. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66716. for (var i = 0; i < data.length; i++) {
  66717. for (var j = 0; j < data[i].length; j++) {
  66718. for (var d = 0; d < dim; d++)
  66719. result.vertices.push(data[i][j][d]);
  66720. }
  66721. if (i > 0) {
  66722. holeIndex += data[i - 1].length;
  66723. result.holes.push(holeIndex);
  66724. }
  66725. }
  66726. return result;
  66727. }
  66728. Earcut.flatten = flatten;
  66729. ;
  66730. })(Earcut || (Earcut = {}));
  66731. //# sourceMappingURL=babylon.earcut.js.map
  66732. var BABYLON;
  66733. (function (BABYLON) {
  66734. var IndexedVector2 = /** @class */ (function (_super) {
  66735. __extends(IndexedVector2, _super);
  66736. function IndexedVector2(original, index) {
  66737. var _this = _super.call(this, original.x, original.y) || this;
  66738. _this.index = index;
  66739. return _this;
  66740. }
  66741. return IndexedVector2;
  66742. }(BABYLON.Vector2));
  66743. var PolygonPoints = /** @class */ (function () {
  66744. function PolygonPoints() {
  66745. this.elements = new Array();
  66746. }
  66747. PolygonPoints.prototype.add = function (originalPoints) {
  66748. var _this = this;
  66749. var result = new Array();
  66750. originalPoints.forEach(function (point) {
  66751. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66752. var newPoint = new IndexedVector2(point, _this.elements.length);
  66753. result.push(newPoint);
  66754. _this.elements.push(newPoint);
  66755. }
  66756. });
  66757. return result;
  66758. };
  66759. PolygonPoints.prototype.computeBounds = function () {
  66760. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66761. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66762. this.elements.forEach(function (point) {
  66763. // x
  66764. if (point.x < lmin.x) {
  66765. lmin.x = point.x;
  66766. }
  66767. else if (point.x > lmax.x) {
  66768. lmax.x = point.x;
  66769. }
  66770. // y
  66771. if (point.y < lmin.y) {
  66772. lmin.y = point.y;
  66773. }
  66774. else if (point.y > lmax.y) {
  66775. lmax.y = point.y;
  66776. }
  66777. });
  66778. return {
  66779. min: lmin,
  66780. max: lmax,
  66781. width: lmax.x - lmin.x,
  66782. height: lmax.y - lmin.y
  66783. };
  66784. };
  66785. return PolygonPoints;
  66786. }());
  66787. var Polygon = /** @class */ (function () {
  66788. function Polygon() {
  66789. }
  66790. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66791. return [
  66792. new BABYLON.Vector2(xmin, ymin),
  66793. new BABYLON.Vector2(xmax, ymin),
  66794. new BABYLON.Vector2(xmax, ymax),
  66795. new BABYLON.Vector2(xmin, ymax)
  66796. ];
  66797. };
  66798. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66799. if (cx === void 0) { cx = 0; }
  66800. if (cy === void 0) { cy = 0; }
  66801. if (numberOfSides === void 0) { numberOfSides = 32; }
  66802. var result = new Array();
  66803. var angle = 0;
  66804. var increment = (Math.PI * 2) / numberOfSides;
  66805. for (var i = 0; i < numberOfSides; i++) {
  66806. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66807. angle -= increment;
  66808. }
  66809. return result;
  66810. };
  66811. Polygon.Parse = function (input) {
  66812. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66813. var i, result = [];
  66814. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66815. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66816. }
  66817. return result;
  66818. };
  66819. Polygon.StartingAt = function (x, y) {
  66820. return BABYLON.Path2.StartingAt(x, y);
  66821. };
  66822. return Polygon;
  66823. }());
  66824. BABYLON.Polygon = Polygon;
  66825. var PolygonMeshBuilder = /** @class */ (function () {
  66826. function PolygonMeshBuilder(name, contours, scene) {
  66827. this._points = new PolygonPoints();
  66828. this._outlinepoints = new PolygonPoints();
  66829. this._holes = new Array();
  66830. this._epoints = new Array();
  66831. this._eholes = new Array();
  66832. this._name = name;
  66833. this._scene = scene;
  66834. var points;
  66835. if (contours instanceof BABYLON.Path2) {
  66836. points = contours.getPoints();
  66837. }
  66838. else {
  66839. points = contours;
  66840. }
  66841. this._addToepoint(points);
  66842. this._points.add(points);
  66843. this._outlinepoints.add(points);
  66844. }
  66845. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66846. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66847. var p = points_1[_i];
  66848. this._epoints.push(p.x, p.y);
  66849. }
  66850. };
  66851. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66852. this._points.add(hole);
  66853. var holepoints = new PolygonPoints();
  66854. holepoints.add(hole);
  66855. this._holes.push(holepoints);
  66856. this._eholes.push(this._epoints.length / 2);
  66857. this._addToepoint(hole);
  66858. return this;
  66859. };
  66860. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66861. var _this = this;
  66862. if (updatable === void 0) { updatable = false; }
  66863. if (depth === void 0) { depth = 0; }
  66864. var result = new BABYLON.Mesh(this._name, this._scene);
  66865. var normals = new Array();
  66866. var positions = new Array();
  66867. var uvs = new Array();
  66868. var bounds = this._points.computeBounds();
  66869. this._points.elements.forEach(function (p) {
  66870. normals.push(0, 1.0, 0);
  66871. positions.push(p.x, 0, p.y);
  66872. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66873. });
  66874. var indices = new Array();
  66875. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66876. for (var i = 0; i < res.length; i++) {
  66877. indices.push(res[i]);
  66878. }
  66879. if (depth > 0) {
  66880. var positionscount = (positions.length / 3); //get the current pointcount
  66881. this._points.elements.forEach(function (p) {
  66882. normals.push(0, -1.0, 0);
  66883. positions.push(p.x, -depth, p.y);
  66884. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66885. });
  66886. var totalCount = indices.length;
  66887. for (var i = 0; i < totalCount; i += 3) {
  66888. var i0 = indices[i + 0];
  66889. var i1 = indices[i + 1];
  66890. var i2 = indices[i + 2];
  66891. indices.push(i2 + positionscount);
  66892. indices.push(i1 + positionscount);
  66893. indices.push(i0 + positionscount);
  66894. }
  66895. //Add the sides
  66896. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66897. this._holes.forEach(function (hole) {
  66898. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66899. });
  66900. }
  66901. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66902. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66903. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66904. result.setIndices(indices);
  66905. return result;
  66906. };
  66907. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66908. var StartIndex = positions.length / 3;
  66909. var ulength = 0;
  66910. for (var i = 0; i < points.elements.length; i++) {
  66911. var p = points.elements[i];
  66912. var p1;
  66913. if ((i + 1) > points.elements.length - 1) {
  66914. p1 = points.elements[0];
  66915. }
  66916. else {
  66917. p1 = points.elements[i + 1];
  66918. }
  66919. positions.push(p.x, 0, p.y);
  66920. positions.push(p.x, -depth, p.y);
  66921. positions.push(p1.x, 0, p1.y);
  66922. positions.push(p1.x, -depth, p1.y);
  66923. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66924. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66925. var v3 = v2.subtract(v1);
  66926. var v4 = new BABYLON.Vector3(0, 1, 0);
  66927. var vn = BABYLON.Vector3.Cross(v3, v4);
  66928. vn = vn.normalize();
  66929. uvs.push(ulength / bounds.width, 0);
  66930. uvs.push(ulength / bounds.width, 1);
  66931. ulength += v3.length();
  66932. uvs.push((ulength / bounds.width), 0);
  66933. uvs.push((ulength / bounds.width), 1);
  66934. if (!flip) {
  66935. normals.push(-vn.x, -vn.y, -vn.z);
  66936. normals.push(-vn.x, -vn.y, -vn.z);
  66937. normals.push(-vn.x, -vn.y, -vn.z);
  66938. normals.push(-vn.x, -vn.y, -vn.z);
  66939. indices.push(StartIndex);
  66940. indices.push(StartIndex + 1);
  66941. indices.push(StartIndex + 2);
  66942. indices.push(StartIndex + 1);
  66943. indices.push(StartIndex + 3);
  66944. indices.push(StartIndex + 2);
  66945. }
  66946. else {
  66947. normals.push(vn.x, vn.y, vn.z);
  66948. normals.push(vn.x, vn.y, vn.z);
  66949. normals.push(vn.x, vn.y, vn.z);
  66950. normals.push(vn.x, vn.y, vn.z);
  66951. indices.push(StartIndex);
  66952. indices.push(StartIndex + 2);
  66953. indices.push(StartIndex + 1);
  66954. indices.push(StartIndex + 1);
  66955. indices.push(StartIndex + 2);
  66956. indices.push(StartIndex + 3);
  66957. }
  66958. StartIndex += 4;
  66959. }
  66960. ;
  66961. };
  66962. return PolygonMeshBuilder;
  66963. }());
  66964. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66965. })(BABYLON || (BABYLON = {}));
  66966. //# sourceMappingURL=babylon.polygonMesh.js.map
  66967. var BABYLON;
  66968. (function (BABYLON) {
  66969. // Unique ID when we import meshes from Babylon to CSG
  66970. var currentCSGMeshId = 0;
  66971. // # class Vertex
  66972. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66973. // one to provide additional features like texture coordinates and vertex
  66974. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66975. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66976. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66977. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66978. // is not used anywhere else.
  66979. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66980. var Vertex = /** @class */ (function () {
  66981. function Vertex(pos, normal, uv) {
  66982. this.pos = pos;
  66983. this.normal = normal;
  66984. this.uv = uv;
  66985. }
  66986. Vertex.prototype.clone = function () {
  66987. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66988. };
  66989. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66990. // orientation of a polygon is flipped.
  66991. Vertex.prototype.flip = function () {
  66992. this.normal = this.normal.scale(-1);
  66993. };
  66994. // Create a new vertex between this vertex and `other` by linearly
  66995. // interpolating all properties using a parameter of `t`. Subclasses should
  66996. // override this to interpolate additional properties.
  66997. Vertex.prototype.interpolate = function (other, t) {
  66998. 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));
  66999. };
  67000. return Vertex;
  67001. }());
  67002. // # class Plane
  67003. // Represents a plane in 3D space.
  67004. var Plane = /** @class */ (function () {
  67005. function Plane(normal, w) {
  67006. this.normal = normal;
  67007. this.w = w;
  67008. }
  67009. Plane.FromPoints = function (a, b, c) {
  67010. var v0 = c.subtract(a);
  67011. var v1 = b.subtract(a);
  67012. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  67013. return null;
  67014. }
  67015. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67016. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67017. };
  67018. Plane.prototype.clone = function () {
  67019. return new Plane(this.normal.clone(), this.w);
  67020. };
  67021. Plane.prototype.flip = function () {
  67022. this.normal.scaleInPlace(-1);
  67023. this.w = -this.w;
  67024. };
  67025. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67026. // fragments in the appropriate lists. Coplanar polygons go into either
  67027. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67028. // respect to this plane. Polygons in front or in back of this plane go into
  67029. // either `front` or `back`.
  67030. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67031. var COPLANAR = 0;
  67032. var FRONT = 1;
  67033. var BACK = 2;
  67034. var SPANNING = 3;
  67035. // Classify each point as well as the entire polygon into one of the above
  67036. // four classes.
  67037. var polygonType = 0;
  67038. var types = [];
  67039. var i;
  67040. var t;
  67041. for (i = 0; i < polygon.vertices.length; i++) {
  67042. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67043. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67044. polygonType |= type;
  67045. types.push(type);
  67046. }
  67047. // Put the polygon in the correct list, splitting it when necessary.
  67048. switch (polygonType) {
  67049. case COPLANAR:
  67050. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67051. break;
  67052. case FRONT:
  67053. front.push(polygon);
  67054. break;
  67055. case BACK:
  67056. back.push(polygon);
  67057. break;
  67058. case SPANNING:
  67059. var f = [], b = [];
  67060. for (i = 0; i < polygon.vertices.length; i++) {
  67061. var j = (i + 1) % polygon.vertices.length;
  67062. var ti = types[i], tj = types[j];
  67063. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67064. if (ti !== BACK)
  67065. f.push(vi);
  67066. if (ti !== FRONT)
  67067. b.push(ti !== BACK ? vi.clone() : vi);
  67068. if ((ti | tj) === SPANNING) {
  67069. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67070. var v = vi.interpolate(vj, t);
  67071. f.push(v);
  67072. b.push(v.clone());
  67073. }
  67074. }
  67075. var poly;
  67076. if (f.length >= 3) {
  67077. poly = new Polygon(f, polygon.shared);
  67078. if (poly.plane)
  67079. front.push(poly);
  67080. }
  67081. if (b.length >= 3) {
  67082. poly = new Polygon(b, polygon.shared);
  67083. if (poly.plane)
  67084. back.push(poly);
  67085. }
  67086. break;
  67087. }
  67088. };
  67089. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67090. // point is on the plane.
  67091. Plane.EPSILON = 1e-5;
  67092. return Plane;
  67093. }());
  67094. // # class Polygon
  67095. // Represents a convex polygon. The vertices used to initialize a polygon must
  67096. // be coplanar and form a convex loop.
  67097. //
  67098. // Each convex polygon has a `shared` property, which is shared between all
  67099. // polygons that are clones of each other or were split from the same polygon.
  67100. // This can be used to define per-polygon properties (such as surface color).
  67101. var Polygon = /** @class */ (function () {
  67102. function Polygon(vertices, shared) {
  67103. this.vertices = vertices;
  67104. this.shared = shared;
  67105. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67106. }
  67107. Polygon.prototype.clone = function () {
  67108. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67109. return new Polygon(vertices, this.shared);
  67110. };
  67111. Polygon.prototype.flip = function () {
  67112. this.vertices.reverse().map(function (v) { v.flip(); });
  67113. this.plane.flip();
  67114. };
  67115. return Polygon;
  67116. }());
  67117. // # class Node
  67118. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67119. // by picking a polygon to split along. That polygon (and all other coplanar
  67120. // polygons) are added directly to that node and the other polygons are added to
  67121. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67122. // no distinction between internal and leaf nodes.
  67123. var Node = /** @class */ (function () {
  67124. function Node(polygons) {
  67125. this.plane = null;
  67126. this.front = null;
  67127. this.back = null;
  67128. this.polygons = new Array();
  67129. if (polygons) {
  67130. this.build(polygons);
  67131. }
  67132. }
  67133. Node.prototype.clone = function () {
  67134. var node = new Node();
  67135. node.plane = this.plane && this.plane.clone();
  67136. node.front = this.front && this.front.clone();
  67137. node.back = this.back && this.back.clone();
  67138. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67139. return node;
  67140. };
  67141. // Convert solid space to empty space and empty space to solid space.
  67142. Node.prototype.invert = function () {
  67143. for (var i = 0; i < this.polygons.length; i++) {
  67144. this.polygons[i].flip();
  67145. }
  67146. if (this.plane) {
  67147. this.plane.flip();
  67148. }
  67149. if (this.front) {
  67150. this.front.invert();
  67151. }
  67152. if (this.back) {
  67153. this.back.invert();
  67154. }
  67155. var temp = this.front;
  67156. this.front = this.back;
  67157. this.back = temp;
  67158. };
  67159. // Recursively remove all polygons in `polygons` that are inside this BSP
  67160. // tree.
  67161. Node.prototype.clipPolygons = function (polygons) {
  67162. if (!this.plane)
  67163. return polygons.slice();
  67164. var front = new Array(), back = new Array();
  67165. for (var i = 0; i < polygons.length; i++) {
  67166. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67167. }
  67168. if (this.front) {
  67169. front = this.front.clipPolygons(front);
  67170. }
  67171. if (this.back) {
  67172. back = this.back.clipPolygons(back);
  67173. }
  67174. else {
  67175. back = [];
  67176. }
  67177. return front.concat(back);
  67178. };
  67179. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67180. // `bsp`.
  67181. Node.prototype.clipTo = function (bsp) {
  67182. this.polygons = bsp.clipPolygons(this.polygons);
  67183. if (this.front)
  67184. this.front.clipTo(bsp);
  67185. if (this.back)
  67186. this.back.clipTo(bsp);
  67187. };
  67188. // Return a list of all polygons in this BSP tree.
  67189. Node.prototype.allPolygons = function () {
  67190. var polygons = this.polygons.slice();
  67191. if (this.front)
  67192. polygons = polygons.concat(this.front.allPolygons());
  67193. if (this.back)
  67194. polygons = polygons.concat(this.back.allPolygons());
  67195. return polygons;
  67196. };
  67197. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67198. // new polygons are filtered down to the bottom of the tree and become new
  67199. // nodes there. Each set of polygons is partitioned using the first polygon
  67200. // (no heuristic is used to pick a good split).
  67201. Node.prototype.build = function (polygons) {
  67202. if (!polygons.length)
  67203. return;
  67204. if (!this.plane)
  67205. this.plane = polygons[0].plane.clone();
  67206. var front = new Array(), back = new Array();
  67207. for (var i = 0; i < polygons.length; i++) {
  67208. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67209. }
  67210. if (front.length) {
  67211. if (!this.front)
  67212. this.front = new Node();
  67213. this.front.build(front);
  67214. }
  67215. if (back.length) {
  67216. if (!this.back)
  67217. this.back = new Node();
  67218. this.back.build(back);
  67219. }
  67220. };
  67221. return Node;
  67222. }());
  67223. var CSG = /** @class */ (function () {
  67224. function CSG() {
  67225. this.polygons = new Array();
  67226. }
  67227. // Convert BABYLON.Mesh to BABYLON.CSG
  67228. CSG.FromMesh = function (mesh) {
  67229. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67230. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67231. if (mesh instanceof BABYLON.Mesh) {
  67232. mesh.computeWorldMatrix(true);
  67233. matrix = mesh.getWorldMatrix();
  67234. meshPosition = mesh.position.clone();
  67235. meshRotation = mesh.rotation.clone();
  67236. if (mesh.rotationQuaternion) {
  67237. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67238. }
  67239. meshScaling = mesh.scaling.clone();
  67240. }
  67241. else {
  67242. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67243. }
  67244. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67245. var subMeshes = mesh.subMeshes;
  67246. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67247. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67248. vertices = [];
  67249. for (var j = 0; j < 3; j++) {
  67250. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67251. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67252. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67253. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67254. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67255. vertex = new Vertex(position, normal, uv);
  67256. vertices.push(vertex);
  67257. }
  67258. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67259. // To handle the case of degenerated triangle
  67260. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67261. if (polygon.plane)
  67262. polygons.push(polygon);
  67263. }
  67264. }
  67265. var csg = CSG.FromPolygons(polygons);
  67266. csg.matrix = matrix;
  67267. csg.position = meshPosition;
  67268. csg.rotation = meshRotation;
  67269. csg.scaling = meshScaling;
  67270. csg.rotationQuaternion = meshRotationQuaternion;
  67271. currentCSGMeshId++;
  67272. return csg;
  67273. };
  67274. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67275. CSG.FromPolygons = function (polygons) {
  67276. var csg = new CSG();
  67277. csg.polygons = polygons;
  67278. return csg;
  67279. };
  67280. CSG.prototype.clone = function () {
  67281. var csg = new CSG();
  67282. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67283. csg.copyTransformAttributes(this);
  67284. return csg;
  67285. };
  67286. CSG.prototype.union = function (csg) {
  67287. var a = new Node(this.clone().polygons);
  67288. var b = new Node(csg.clone().polygons);
  67289. a.clipTo(b);
  67290. b.clipTo(a);
  67291. b.invert();
  67292. b.clipTo(a);
  67293. b.invert();
  67294. a.build(b.allPolygons());
  67295. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67296. };
  67297. CSG.prototype.unionInPlace = function (csg) {
  67298. var a = new Node(this.polygons);
  67299. var b = new Node(csg.polygons);
  67300. a.clipTo(b);
  67301. b.clipTo(a);
  67302. b.invert();
  67303. b.clipTo(a);
  67304. b.invert();
  67305. a.build(b.allPolygons());
  67306. this.polygons = a.allPolygons();
  67307. };
  67308. CSG.prototype.subtract = function (csg) {
  67309. var a = new Node(this.clone().polygons);
  67310. var b = new Node(csg.clone().polygons);
  67311. a.invert();
  67312. a.clipTo(b);
  67313. b.clipTo(a);
  67314. b.invert();
  67315. b.clipTo(a);
  67316. b.invert();
  67317. a.build(b.allPolygons());
  67318. a.invert();
  67319. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67320. };
  67321. CSG.prototype.subtractInPlace = function (csg) {
  67322. var a = new Node(this.polygons);
  67323. var b = new Node(csg.polygons);
  67324. a.invert();
  67325. a.clipTo(b);
  67326. b.clipTo(a);
  67327. b.invert();
  67328. b.clipTo(a);
  67329. b.invert();
  67330. a.build(b.allPolygons());
  67331. a.invert();
  67332. this.polygons = a.allPolygons();
  67333. };
  67334. CSG.prototype.intersect = function (csg) {
  67335. var a = new Node(this.clone().polygons);
  67336. var b = new Node(csg.clone().polygons);
  67337. a.invert();
  67338. b.clipTo(a);
  67339. b.invert();
  67340. a.clipTo(b);
  67341. b.clipTo(a);
  67342. a.build(b.allPolygons());
  67343. a.invert();
  67344. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67345. };
  67346. CSG.prototype.intersectInPlace = function (csg) {
  67347. var a = new Node(this.polygons);
  67348. var b = new Node(csg.polygons);
  67349. a.invert();
  67350. b.clipTo(a);
  67351. b.invert();
  67352. a.clipTo(b);
  67353. b.clipTo(a);
  67354. a.build(b.allPolygons());
  67355. a.invert();
  67356. this.polygons = a.allPolygons();
  67357. };
  67358. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67359. // not modified.
  67360. CSG.prototype.inverse = function () {
  67361. var csg = this.clone();
  67362. csg.inverseInPlace();
  67363. return csg;
  67364. };
  67365. CSG.prototype.inverseInPlace = function () {
  67366. this.polygons.map(function (p) { p.flip(); });
  67367. };
  67368. // This is used to keep meshes transformations so they can be restored
  67369. // when we build back a Babylon Mesh
  67370. // NB : All CSG operations are performed in world coordinates
  67371. CSG.prototype.copyTransformAttributes = function (csg) {
  67372. this.matrix = csg.matrix;
  67373. this.position = csg.position;
  67374. this.rotation = csg.rotation;
  67375. this.scaling = csg.scaling;
  67376. this.rotationQuaternion = csg.rotationQuaternion;
  67377. return this;
  67378. };
  67379. // Build Raw mesh from CSG
  67380. // Coordinates here are in world space
  67381. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67382. var matrix = this.matrix.clone();
  67383. matrix.invert();
  67384. 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;
  67385. if (keepSubMeshes) {
  67386. // Sort Polygons, since subMeshes are indices range
  67387. polygons.sort(function (a, b) {
  67388. if (a.shared.meshId === b.shared.meshId) {
  67389. return a.shared.subMeshId - b.shared.subMeshId;
  67390. }
  67391. else {
  67392. return a.shared.meshId - b.shared.meshId;
  67393. }
  67394. });
  67395. }
  67396. for (var i = 0, il = polygons.length; i < il; i++) {
  67397. polygon = polygons[i];
  67398. // Building SubMeshes
  67399. if (!subMesh_dict[polygon.shared.meshId]) {
  67400. subMesh_dict[polygon.shared.meshId] = {};
  67401. }
  67402. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67403. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67404. indexStart: +Infinity,
  67405. indexEnd: -Infinity,
  67406. materialIndex: polygon.shared.materialIndex
  67407. };
  67408. }
  67409. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67410. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67411. polygonIndices[0] = 0;
  67412. polygonIndices[1] = j - 1;
  67413. polygonIndices[2] = j;
  67414. for (var k = 0; k < 3; k++) {
  67415. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67416. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67417. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67418. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67419. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67420. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67421. // Check if 2 points can be merged
  67422. if (!(typeof vertex_idx !== 'undefined' &&
  67423. normals[vertex_idx * 3] === localNormal.x &&
  67424. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67425. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67426. uvs[vertex_idx * 2] === uv.x &&
  67427. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67428. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67429. uvs.push(uv.x, uv.y);
  67430. normals.push(normal.x, normal.y, normal.z);
  67431. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67432. }
  67433. indices.push(vertex_idx);
  67434. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67435. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67436. currentIndex++;
  67437. }
  67438. }
  67439. }
  67440. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67441. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67442. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67443. mesh.setIndices(indices, null);
  67444. if (keepSubMeshes) {
  67445. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67446. var materialIndexOffset = 0, materialMaxIndex;
  67447. mesh.subMeshes = new Array();
  67448. for (var m in subMesh_dict) {
  67449. materialMaxIndex = -1;
  67450. for (var sm in subMesh_dict[m]) {
  67451. subMesh_obj = subMesh_dict[m][sm];
  67452. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67453. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67454. }
  67455. materialIndexOffset += ++materialMaxIndex;
  67456. }
  67457. }
  67458. return mesh;
  67459. };
  67460. // Build Mesh from CSG taking material and transforms into account
  67461. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67462. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67463. mesh.material = material;
  67464. mesh.position.copyFrom(this.position);
  67465. mesh.rotation.copyFrom(this.rotation);
  67466. if (this.rotationQuaternion) {
  67467. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67468. }
  67469. mesh.scaling.copyFrom(this.scaling);
  67470. mesh.computeWorldMatrix(true);
  67471. return mesh;
  67472. };
  67473. return CSG;
  67474. }());
  67475. BABYLON.CSG = CSG;
  67476. })(BABYLON || (BABYLON = {}));
  67477. //# sourceMappingURL=babylon.csg.js.map
  67478. var BABYLON;
  67479. (function (BABYLON) {
  67480. var LensFlare = /** @class */ (function () {
  67481. function LensFlare(size, position, color, imgUrl, system) {
  67482. this.size = size;
  67483. this.position = position;
  67484. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67485. this.color = color || new BABYLON.Color3(1, 1, 1);
  67486. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67487. this._system = system;
  67488. system.lensFlares.push(this);
  67489. }
  67490. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67491. return new LensFlare(size, position, color, imgUrl, system);
  67492. };
  67493. LensFlare.prototype.dispose = function () {
  67494. if (this.texture) {
  67495. this.texture.dispose();
  67496. }
  67497. // Remove from scene
  67498. var index = this._system.lensFlares.indexOf(this);
  67499. this._system.lensFlares.splice(index, 1);
  67500. };
  67501. ;
  67502. return LensFlare;
  67503. }());
  67504. BABYLON.LensFlare = LensFlare;
  67505. })(BABYLON || (BABYLON = {}));
  67506. //# sourceMappingURL=babylon.lensFlare.js.map
  67507. var BABYLON;
  67508. (function (BABYLON) {
  67509. var LensFlareSystem = /** @class */ (function () {
  67510. function LensFlareSystem(name, emitter, scene) {
  67511. this.name = name;
  67512. this.lensFlares = new Array();
  67513. this.borderLimit = 300;
  67514. this.viewportBorder = 0;
  67515. this.layerMask = 0x0FFFFFFF;
  67516. this._vertexBuffers = {};
  67517. this._isEnabled = true;
  67518. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67519. this._emitter = emitter;
  67520. this.id = name;
  67521. scene.lensFlareSystems.push(this);
  67522. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67523. var engine = scene.getEngine();
  67524. // VBO
  67525. var vertices = [];
  67526. vertices.push(1, 1);
  67527. vertices.push(-1, 1);
  67528. vertices.push(-1, -1);
  67529. vertices.push(1, -1);
  67530. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67531. // Indices
  67532. var indices = [];
  67533. indices.push(0);
  67534. indices.push(1);
  67535. indices.push(2);
  67536. indices.push(0);
  67537. indices.push(2);
  67538. indices.push(3);
  67539. this._indexBuffer = engine.createIndexBuffer(indices);
  67540. // Effects
  67541. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67542. }
  67543. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67544. get: function () {
  67545. return this._isEnabled;
  67546. },
  67547. set: function (value) {
  67548. this._isEnabled = value;
  67549. },
  67550. enumerable: true,
  67551. configurable: true
  67552. });
  67553. LensFlareSystem.prototype.getScene = function () {
  67554. return this._scene;
  67555. };
  67556. LensFlareSystem.prototype.getEmitter = function () {
  67557. return this._emitter;
  67558. };
  67559. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67560. this._emitter = newEmitter;
  67561. };
  67562. LensFlareSystem.prototype.getEmitterPosition = function () {
  67563. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67564. };
  67565. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67566. var position = this.getEmitterPosition();
  67567. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67568. this._positionX = position.x;
  67569. this._positionY = position.y;
  67570. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67571. if (this.viewportBorder > 0) {
  67572. globalViewport.x -= this.viewportBorder;
  67573. globalViewport.y -= this.viewportBorder;
  67574. globalViewport.width += this.viewportBorder * 2;
  67575. globalViewport.height += this.viewportBorder * 2;
  67576. position.x += this.viewportBorder;
  67577. position.y += this.viewportBorder;
  67578. this._positionX += this.viewportBorder;
  67579. this._positionY += this.viewportBorder;
  67580. }
  67581. if (position.z > 0) {
  67582. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67583. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67584. return true;
  67585. }
  67586. return true;
  67587. }
  67588. return false;
  67589. };
  67590. LensFlareSystem.prototype._isVisible = function () {
  67591. if (!this._isEnabled || !this._scene.activeCamera) {
  67592. return false;
  67593. }
  67594. var emitterPosition = this.getEmitterPosition();
  67595. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67596. var distance = direction.length();
  67597. direction.normalize();
  67598. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67599. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67600. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67601. };
  67602. LensFlareSystem.prototype.render = function () {
  67603. if (!this._effect.isReady() || !this._scene.activeCamera)
  67604. return false;
  67605. var engine = this._scene.getEngine();
  67606. var viewport = this._scene.activeCamera.viewport;
  67607. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67608. // Position
  67609. if (!this.computeEffectivePosition(globalViewport)) {
  67610. return false;
  67611. }
  67612. // Visibility
  67613. if (!this._isVisible()) {
  67614. return false;
  67615. }
  67616. // Intensity
  67617. var awayX;
  67618. var awayY;
  67619. if (this._positionX < this.borderLimit + globalViewport.x) {
  67620. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67621. }
  67622. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67623. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67624. }
  67625. else {
  67626. awayX = 0;
  67627. }
  67628. if (this._positionY < this.borderLimit + globalViewport.y) {
  67629. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67630. }
  67631. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67632. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67633. }
  67634. else {
  67635. awayY = 0;
  67636. }
  67637. var away = (awayX > awayY) ? awayX : awayY;
  67638. away -= this.viewportBorder;
  67639. if (away > this.borderLimit) {
  67640. away = this.borderLimit;
  67641. }
  67642. var intensity = 1.0 - (away / this.borderLimit);
  67643. if (intensity < 0) {
  67644. return false;
  67645. }
  67646. if (intensity > 1.0) {
  67647. intensity = 1.0;
  67648. }
  67649. if (this.viewportBorder > 0) {
  67650. globalViewport.x += this.viewportBorder;
  67651. globalViewport.y += this.viewportBorder;
  67652. globalViewport.width -= this.viewportBorder * 2;
  67653. globalViewport.height -= this.viewportBorder * 2;
  67654. this._positionX -= this.viewportBorder;
  67655. this._positionY -= this.viewportBorder;
  67656. }
  67657. // Position
  67658. var centerX = globalViewport.x + globalViewport.width / 2;
  67659. var centerY = globalViewport.y + globalViewport.height / 2;
  67660. var distX = centerX - this._positionX;
  67661. var distY = centerY - this._positionY;
  67662. // Effects
  67663. engine.enableEffect(this._effect);
  67664. engine.setState(false);
  67665. engine.setDepthBuffer(false);
  67666. // VBOs
  67667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67668. // Flares
  67669. for (var index = 0; index < this.lensFlares.length; index++) {
  67670. var flare = this.lensFlares[index];
  67671. engine.setAlphaMode(flare.alphaMode);
  67672. var x = centerX - (distX * flare.position);
  67673. var y = centerY - (distY * flare.position);
  67674. var cw = flare.size;
  67675. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67676. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67677. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67678. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67679. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67680. // Texture
  67681. this._effect.setTexture("textureSampler", flare.texture);
  67682. // Color
  67683. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67684. // Draw order
  67685. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67686. }
  67687. engine.setDepthBuffer(true);
  67688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67689. return true;
  67690. };
  67691. LensFlareSystem.prototype.dispose = function () {
  67692. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67693. if (vertexBuffer) {
  67694. vertexBuffer.dispose();
  67695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67696. }
  67697. if (this._indexBuffer) {
  67698. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67699. this._indexBuffer = null;
  67700. }
  67701. while (this.lensFlares.length) {
  67702. this.lensFlares[0].dispose();
  67703. }
  67704. // Remove from scene
  67705. var index = this._scene.lensFlareSystems.indexOf(this);
  67706. this._scene.lensFlareSystems.splice(index, 1);
  67707. };
  67708. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67709. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67710. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67711. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67712. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67713. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67714. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67715. var parsedFlare = parsedLensFlareSystem.flares[index];
  67716. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67717. }
  67718. return lensFlareSystem;
  67719. };
  67720. LensFlareSystem.prototype.serialize = function () {
  67721. var serializationObject = {};
  67722. serializationObject.id = this.id;
  67723. serializationObject.name = this.name;
  67724. serializationObject.emitterId = this.getEmitter().id;
  67725. serializationObject.borderLimit = this.borderLimit;
  67726. serializationObject.flares = [];
  67727. for (var index = 0; index < this.lensFlares.length; index++) {
  67728. var flare = this.lensFlares[index];
  67729. serializationObject.flares.push({
  67730. size: flare.size,
  67731. position: flare.position,
  67732. color: flare.color.asArray(),
  67733. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67734. });
  67735. }
  67736. return serializationObject;
  67737. };
  67738. return LensFlareSystem;
  67739. }());
  67740. BABYLON.LensFlareSystem = LensFlareSystem;
  67741. })(BABYLON || (BABYLON = {}));
  67742. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67743. var BABYLON;
  67744. (function (BABYLON) {
  67745. /**
  67746. * This is a holder class for the physics joint created by the physics plugin.
  67747. * It holds a set of functions to control the underlying joint.
  67748. */
  67749. var PhysicsJoint = /** @class */ (function () {
  67750. function PhysicsJoint(type, jointData) {
  67751. this.type = type;
  67752. this.jointData = jointData;
  67753. jointData.nativeParams = jointData.nativeParams || {};
  67754. }
  67755. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67756. get: function () {
  67757. return this._physicsJoint;
  67758. },
  67759. set: function (newJoint) {
  67760. if (this._physicsJoint) {
  67761. //remove from the wolrd
  67762. }
  67763. this._physicsJoint = newJoint;
  67764. },
  67765. enumerable: true,
  67766. configurable: true
  67767. });
  67768. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67769. set: function (physicsPlugin) {
  67770. this._physicsPlugin = physicsPlugin;
  67771. },
  67772. enumerable: true,
  67773. configurable: true
  67774. });
  67775. /**
  67776. * Execute a function that is physics-plugin specific.
  67777. * @param {Function} func the function that will be executed.
  67778. * It accepts two parameters: the physics world and the physics joint.
  67779. */
  67780. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67781. func(this._physicsPlugin.world, this._physicsJoint);
  67782. };
  67783. //TODO check if the native joints are the same
  67784. //Joint Types
  67785. PhysicsJoint.DistanceJoint = 0;
  67786. PhysicsJoint.HingeJoint = 1;
  67787. PhysicsJoint.BallAndSocketJoint = 2;
  67788. PhysicsJoint.WheelJoint = 3;
  67789. PhysicsJoint.SliderJoint = 4;
  67790. //OIMO
  67791. PhysicsJoint.PrismaticJoint = 5;
  67792. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67793. PhysicsJoint.UniversalJoint = 6;
  67794. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67795. //Cannon
  67796. //Similar to a Ball-Joint. Different in params
  67797. PhysicsJoint.PointToPointJoint = 8;
  67798. //Cannon only at the moment
  67799. PhysicsJoint.SpringJoint = 9;
  67800. PhysicsJoint.LockJoint = 10;
  67801. return PhysicsJoint;
  67802. }());
  67803. BABYLON.PhysicsJoint = PhysicsJoint;
  67804. /**
  67805. * A class representing a physics distance joint.
  67806. */
  67807. var DistanceJoint = /** @class */ (function (_super) {
  67808. __extends(DistanceJoint, _super);
  67809. function DistanceJoint(jointData) {
  67810. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67811. }
  67812. /**
  67813. * Update the predefined distance.
  67814. */
  67815. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67816. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67817. };
  67818. return DistanceJoint;
  67819. }(PhysicsJoint));
  67820. BABYLON.DistanceJoint = DistanceJoint;
  67821. var MotorEnabledJoint = /** @class */ (function (_super) {
  67822. __extends(MotorEnabledJoint, _super);
  67823. function MotorEnabledJoint(type, jointData) {
  67824. return _super.call(this, type, jointData) || this;
  67825. }
  67826. /**
  67827. * Set the motor values.
  67828. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67829. * @param {number} force the force to apply
  67830. * @param {number} maxForce max force for this motor.
  67831. */
  67832. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67833. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67834. };
  67835. /**
  67836. * Set the motor's limits.
  67837. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67838. */
  67839. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67840. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67841. };
  67842. return MotorEnabledJoint;
  67843. }(PhysicsJoint));
  67844. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67845. /**
  67846. * This class represents a single hinge physics joint
  67847. */
  67848. var HingeJoint = /** @class */ (function (_super) {
  67849. __extends(HingeJoint, _super);
  67850. function HingeJoint(jointData) {
  67851. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67852. }
  67853. /**
  67854. * Set the motor values.
  67855. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67856. * @param {number} force the force to apply
  67857. * @param {number} maxForce max force for this motor.
  67858. */
  67859. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67860. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67861. };
  67862. /**
  67863. * Set the motor's limits.
  67864. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67865. */
  67866. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67867. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67868. };
  67869. return HingeJoint;
  67870. }(MotorEnabledJoint));
  67871. BABYLON.HingeJoint = HingeJoint;
  67872. /**
  67873. * This class represents a dual hinge physics joint (same as wheel joint)
  67874. */
  67875. var Hinge2Joint = /** @class */ (function (_super) {
  67876. __extends(Hinge2Joint, _super);
  67877. function Hinge2Joint(jointData) {
  67878. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67879. }
  67880. /**
  67881. * Set the motor values.
  67882. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67883. * @param {number} force the force to apply
  67884. * @param {number} maxForce max force for this motor.
  67885. * @param {motorIndex} the motor's index, 0 or 1.
  67886. */
  67887. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67888. if (motorIndex === void 0) { motorIndex = 0; }
  67889. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67890. };
  67891. /**
  67892. * Set the motor limits.
  67893. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67894. * @param {number} upperLimit the upper limit
  67895. * @param {number} lowerLimit lower limit
  67896. * @param {motorIndex} the motor's index, 0 or 1.
  67897. */
  67898. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67899. if (motorIndex === void 0) { motorIndex = 0; }
  67900. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67901. };
  67902. return Hinge2Joint;
  67903. }(MotorEnabledJoint));
  67904. BABYLON.Hinge2Joint = Hinge2Joint;
  67905. })(BABYLON || (BABYLON = {}));
  67906. //# sourceMappingURL=babylon.physicsJoint.js.map
  67907. var BABYLON;
  67908. (function (BABYLON) {
  67909. var PhysicsImpostor = /** @class */ (function () {
  67910. function PhysicsImpostor(object, type, _options, _scene) {
  67911. if (_options === void 0) { _options = { mass: 0 }; }
  67912. var _this = this;
  67913. this.object = object;
  67914. this.type = type;
  67915. this._options = _options;
  67916. this._scene = _scene;
  67917. this._bodyUpdateRequired = false;
  67918. this._onBeforePhysicsStepCallbacks = new Array();
  67919. this._onAfterPhysicsStepCallbacks = new Array();
  67920. this._onPhysicsCollideCallbacks = [];
  67921. this._deltaPosition = BABYLON.Vector3.Zero();
  67922. this._isDisposed = false;
  67923. //temp variables for parent rotation calculations
  67924. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67925. this._tmpQuat = new BABYLON.Quaternion();
  67926. this._tmpQuat2 = new BABYLON.Quaternion();
  67927. /**
  67928. * this function is executed by the physics engine.
  67929. */
  67930. this.beforeStep = function () {
  67931. if (!_this._physicsEngine) {
  67932. return;
  67933. }
  67934. _this.object.translate(_this._deltaPosition, -1);
  67935. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67936. _this.object.computeWorldMatrix(false);
  67937. if (_this.object.parent && _this.object.rotationQuaternion) {
  67938. _this.getParentsRotation();
  67939. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67940. }
  67941. else {
  67942. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67943. }
  67944. if (!_this._options.disableBidirectionalTransformation) {
  67945. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67946. }
  67947. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67948. func(_this);
  67949. });
  67950. };
  67951. /**
  67952. * this function is executed by the physics engine.
  67953. */
  67954. this.afterStep = function () {
  67955. if (!_this._physicsEngine) {
  67956. return;
  67957. }
  67958. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67959. func(_this);
  67960. });
  67961. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67962. // object has now its world rotation. needs to be converted to local.
  67963. if (_this.object.parent && _this.object.rotationQuaternion) {
  67964. _this.getParentsRotation();
  67965. _this._tmpQuat.conjugateInPlace();
  67966. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67967. }
  67968. // take the position set and make it the absolute position of this object.
  67969. _this.object.setAbsolutePosition(_this.object.position);
  67970. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67971. _this.object.translate(_this._deltaPosition, 1);
  67972. };
  67973. /**
  67974. * Legacy collision detection event support
  67975. */
  67976. this.onCollideEvent = null;
  67977. //event and body object due to cannon's event-based architecture.
  67978. this.onCollide = function (e) {
  67979. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67980. return;
  67981. }
  67982. if (!_this._physicsEngine) {
  67983. return;
  67984. }
  67985. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67986. if (otherImpostor) {
  67987. // Legacy collision detection event support
  67988. if (_this.onCollideEvent) {
  67989. _this.onCollideEvent(_this, otherImpostor);
  67990. }
  67991. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67992. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67993. }).forEach(function (obj) {
  67994. obj.callback(_this, otherImpostor);
  67995. });
  67996. }
  67997. };
  67998. //sanity check!
  67999. if (!this.object) {
  68000. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  68001. return;
  68002. }
  68003. //legacy support for old syntax.
  68004. if (!this._scene && object.getScene) {
  68005. this._scene = object.getScene();
  68006. }
  68007. if (!this._scene) {
  68008. return;
  68009. }
  68010. this._physicsEngine = this._scene.getPhysicsEngine();
  68011. if (!this._physicsEngine) {
  68012. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  68013. }
  68014. else {
  68015. //set the object's quaternion, if not set
  68016. if (!this.object.rotationQuaternion) {
  68017. if (this.object.rotation) {
  68018. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68019. }
  68020. else {
  68021. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68022. }
  68023. }
  68024. //default options params
  68025. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68026. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68027. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68028. this._joints = [];
  68029. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68030. if (!this.object.parent || this._options.ignoreParent) {
  68031. this._init();
  68032. }
  68033. else if (this.object.parent.physicsImpostor) {
  68034. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68035. }
  68036. }
  68037. }
  68038. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68039. get: function () {
  68040. return this._isDisposed;
  68041. },
  68042. enumerable: true,
  68043. configurable: true
  68044. });
  68045. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68046. get: function () {
  68047. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68048. },
  68049. set: function (value) {
  68050. this.setMass(value);
  68051. },
  68052. enumerable: true,
  68053. configurable: true
  68054. });
  68055. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68056. get: function () {
  68057. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68058. },
  68059. set: function (value) {
  68060. if (!this._physicsEngine) {
  68061. return;
  68062. }
  68063. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68064. },
  68065. enumerable: true,
  68066. configurable: true
  68067. });
  68068. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68069. get: function () {
  68070. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68071. },
  68072. set: function (value) {
  68073. if (!this._physicsEngine) {
  68074. return;
  68075. }
  68076. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68077. },
  68078. enumerable: true,
  68079. configurable: true
  68080. });
  68081. /**
  68082. * This function will completly initialize this impostor.
  68083. * It will create a new body - but only if this mesh has no parent.
  68084. * If it has, this impostor will not be used other than to define the impostor
  68085. * of the child mesh.
  68086. */
  68087. PhysicsImpostor.prototype._init = function () {
  68088. if (!this._physicsEngine) {
  68089. return;
  68090. }
  68091. this._physicsEngine.removeImpostor(this);
  68092. this.physicsBody = null;
  68093. this._parent = this._parent || this._getPhysicsParent();
  68094. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68095. this._physicsEngine.addImpostor(this);
  68096. }
  68097. };
  68098. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68099. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68100. var parentMesh = this.object.parent;
  68101. return parentMesh.physicsImpostor;
  68102. }
  68103. return null;
  68104. };
  68105. /**
  68106. * Should a new body be generated.
  68107. */
  68108. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68109. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68110. };
  68111. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68112. this.forceUpdate();
  68113. };
  68114. /**
  68115. * Force a regeneration of this or the parent's impostor's body.
  68116. * Use under cautious - This will remove all joints already implemented.
  68117. */
  68118. PhysicsImpostor.prototype.forceUpdate = function () {
  68119. this._init();
  68120. if (this.parent && !this._options.ignoreParent) {
  68121. this.parent.forceUpdate();
  68122. }
  68123. };
  68124. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68125. /*public get mesh(): AbstractMesh {
  68126. return this._mesh;
  68127. }*/
  68128. /**
  68129. * Gets the body that holds this impostor. Either its own, or its parent.
  68130. */
  68131. get: function () {
  68132. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68133. },
  68134. /**
  68135. * Set the physics body. Used mainly by the physics engine/plugin
  68136. */
  68137. set: function (physicsBody) {
  68138. if (this._physicsBody && this._physicsEngine) {
  68139. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68140. }
  68141. this._physicsBody = physicsBody;
  68142. this.resetUpdateFlags();
  68143. },
  68144. enumerable: true,
  68145. configurable: true
  68146. });
  68147. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68148. get: function () {
  68149. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68150. },
  68151. set: function (value) {
  68152. this._parent = value;
  68153. },
  68154. enumerable: true,
  68155. configurable: true
  68156. });
  68157. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68158. this._bodyUpdateRequired = false;
  68159. };
  68160. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68161. if (this.object.getBoundingInfo) {
  68162. var q = this.object.rotationQuaternion;
  68163. //reset rotation
  68164. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68165. //calculate the world matrix with no rotation
  68166. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68167. var boundingInfo = this.object.getBoundingInfo();
  68168. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68169. //bring back the rotation
  68170. this.object.rotationQuaternion = q;
  68171. //calculate the world matrix with the new rotation
  68172. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68173. return size;
  68174. }
  68175. else {
  68176. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68177. }
  68178. };
  68179. PhysicsImpostor.prototype.getObjectCenter = function () {
  68180. if (this.object.getBoundingInfo) {
  68181. var boundingInfo = this.object.getBoundingInfo();
  68182. return boundingInfo.boundingBox.centerWorld;
  68183. }
  68184. else {
  68185. return this.object.position;
  68186. }
  68187. };
  68188. /**
  68189. * Get a specific parametes from the options parameter.
  68190. */
  68191. PhysicsImpostor.prototype.getParam = function (paramName) {
  68192. return this._options[paramName];
  68193. };
  68194. /**
  68195. * Sets a specific parameter in the options given to the physics plugin
  68196. */
  68197. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68198. this._options[paramName] = value;
  68199. this._bodyUpdateRequired = true;
  68200. };
  68201. /**
  68202. * Specifically change the body's mass option. Won't recreate the physics body object
  68203. */
  68204. PhysicsImpostor.prototype.setMass = function (mass) {
  68205. if (this.getParam("mass") !== mass) {
  68206. this.setParam("mass", mass);
  68207. }
  68208. if (this._physicsEngine) {
  68209. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68210. }
  68211. };
  68212. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68213. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68214. };
  68215. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68216. if (this._physicsEngine) {
  68217. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68218. }
  68219. };
  68220. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68221. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68222. };
  68223. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68224. if (this._physicsEngine) {
  68225. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68226. }
  68227. };
  68228. /**
  68229. * Execute a function with the physics plugin native code.
  68230. * Provide a function the will have two variables - the world object and the physics body object.
  68231. */
  68232. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68233. if (this._physicsEngine) {
  68234. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68235. }
  68236. };
  68237. /**
  68238. * Register a function that will be executed before the physics world is stepping forward.
  68239. */
  68240. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68241. this._onBeforePhysicsStepCallbacks.push(func);
  68242. };
  68243. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68244. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68245. if (index > -1) {
  68246. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68247. }
  68248. else {
  68249. BABYLON.Tools.Warn("Function to remove was not found");
  68250. }
  68251. };
  68252. /**
  68253. * Register a function that will be executed after the physics step
  68254. */
  68255. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68256. this._onAfterPhysicsStepCallbacks.push(func);
  68257. };
  68258. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68259. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68260. if (index > -1) {
  68261. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68262. }
  68263. else {
  68264. BABYLON.Tools.Warn("Function to remove was not found");
  68265. }
  68266. };
  68267. /**
  68268. * register a function that will be executed when this impostor collides against a different body.
  68269. */
  68270. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68271. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68272. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68273. };
  68274. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68275. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68276. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68277. if (index > -1) {
  68278. this._onPhysicsCollideCallbacks.splice(index, 1);
  68279. }
  68280. else {
  68281. BABYLON.Tools.Warn("Function to remove was not found");
  68282. }
  68283. };
  68284. PhysicsImpostor.prototype.getParentsRotation = function () {
  68285. var parent = this.object.parent;
  68286. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68287. while (parent) {
  68288. if (parent.rotationQuaternion) {
  68289. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68290. }
  68291. else {
  68292. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68293. }
  68294. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68295. parent = parent.parent;
  68296. }
  68297. return this._tmpQuat;
  68298. };
  68299. /**
  68300. * Apply a force
  68301. */
  68302. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68303. if (this._physicsEngine) {
  68304. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68305. }
  68306. return this;
  68307. };
  68308. /**
  68309. * Apply an impulse
  68310. */
  68311. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68312. if (this._physicsEngine) {
  68313. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68314. }
  68315. return this;
  68316. };
  68317. /**
  68318. * A help function to create a joint.
  68319. */
  68320. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68321. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68322. this.addJoint(otherImpostor, joint);
  68323. return this;
  68324. };
  68325. /**
  68326. * Add a joint to this impostor with a different impostor.
  68327. */
  68328. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68329. this._joints.push({
  68330. otherImpostor: otherImpostor,
  68331. joint: joint
  68332. });
  68333. if (this._physicsEngine) {
  68334. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68335. }
  68336. return this;
  68337. };
  68338. /**
  68339. * Will keep this body still, in a sleep mode.
  68340. */
  68341. PhysicsImpostor.prototype.sleep = function () {
  68342. if (this._physicsEngine) {
  68343. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68344. }
  68345. return this;
  68346. };
  68347. /**
  68348. * Wake the body up.
  68349. */
  68350. PhysicsImpostor.prototype.wakeUp = function () {
  68351. if (this._physicsEngine) {
  68352. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68353. }
  68354. return this;
  68355. };
  68356. PhysicsImpostor.prototype.clone = function (newObject) {
  68357. if (!newObject)
  68358. return null;
  68359. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68360. };
  68361. PhysicsImpostor.prototype.dispose = function () {
  68362. var _this = this;
  68363. //no dispose if no physics engine is available.
  68364. if (!this._physicsEngine) {
  68365. return;
  68366. }
  68367. this._joints.forEach(function (j) {
  68368. if (_this._physicsEngine) {
  68369. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68370. }
  68371. });
  68372. //dispose the physics body
  68373. this._physicsEngine.removeImpostor(this);
  68374. if (this.parent) {
  68375. this.parent.forceUpdate();
  68376. }
  68377. else {
  68378. /*this._object.getChildMeshes().forEach(function(mesh) {
  68379. if (mesh.physicsImpostor) {
  68380. if (disposeChildren) {
  68381. mesh.physicsImpostor.dispose();
  68382. mesh.physicsImpostor = null;
  68383. }
  68384. }
  68385. })*/
  68386. }
  68387. this._isDisposed = true;
  68388. };
  68389. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68390. this._deltaPosition.copyFrom(position);
  68391. };
  68392. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68393. if (!this._deltaRotation) {
  68394. this._deltaRotation = new BABYLON.Quaternion();
  68395. }
  68396. this._deltaRotation.copyFrom(rotation);
  68397. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68398. };
  68399. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68400. if (this._physicsEngine) {
  68401. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68402. }
  68403. return this;
  68404. };
  68405. PhysicsImpostor.prototype.getRadius = function () {
  68406. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68407. };
  68408. /**
  68409. * Sync a bone with this impostor
  68410. * @param bone The bone to sync to the impostor.
  68411. * @param boneMesh The mesh that the bone is influencing.
  68412. * @param jointPivot The pivot of the joint / bone in local space.
  68413. * @param distToJoint Optional distance from the impostor to the joint.
  68414. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68415. */
  68416. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68417. var tempVec = PhysicsImpostor._tmpVecs[0];
  68418. var mesh = this.object;
  68419. if (mesh.rotationQuaternion) {
  68420. if (adjustRotation) {
  68421. var tempQuat = PhysicsImpostor._tmpQuat;
  68422. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68423. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68424. }
  68425. else {
  68426. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68427. }
  68428. }
  68429. tempVec.x = 0;
  68430. tempVec.y = 0;
  68431. tempVec.z = 0;
  68432. if (jointPivot) {
  68433. tempVec.x = jointPivot.x;
  68434. tempVec.y = jointPivot.y;
  68435. tempVec.z = jointPivot.z;
  68436. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68437. if (distToJoint === undefined || distToJoint === null) {
  68438. distToJoint = jointPivot.length();
  68439. }
  68440. tempVec.x *= distToJoint;
  68441. tempVec.y *= distToJoint;
  68442. tempVec.z *= distToJoint;
  68443. }
  68444. if (bone.getParent()) {
  68445. tempVec.addInPlace(mesh.getAbsolutePosition());
  68446. bone.setAbsolutePosition(tempVec, boneMesh);
  68447. }
  68448. else {
  68449. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68450. boneMesh.position.x -= tempVec.x;
  68451. boneMesh.position.y -= tempVec.y;
  68452. boneMesh.position.z -= tempVec.z;
  68453. }
  68454. };
  68455. /**
  68456. * Sync impostor to a bone
  68457. * @param bone The bone that the impostor will be synced to.
  68458. * @param boneMesh The mesh that the bone is influencing.
  68459. * @param jointPivot The pivot of the joint / bone in local space.
  68460. * @param distToJoint Optional distance from the impostor to the joint.
  68461. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68462. * @param boneAxis Optional vector3 axis the bone is aligned with
  68463. */
  68464. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68465. var mesh = this.object;
  68466. if (mesh.rotationQuaternion) {
  68467. if (adjustRotation) {
  68468. var tempQuat = PhysicsImpostor._tmpQuat;
  68469. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68470. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68471. }
  68472. else {
  68473. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68474. }
  68475. }
  68476. var pos = PhysicsImpostor._tmpVecs[0];
  68477. var boneDir = PhysicsImpostor._tmpVecs[1];
  68478. if (!boneAxis) {
  68479. boneAxis = PhysicsImpostor._tmpVecs[2];
  68480. boneAxis.x = 0;
  68481. boneAxis.y = 1;
  68482. boneAxis.z = 0;
  68483. }
  68484. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68485. bone.getAbsolutePositionToRef(boneMesh, pos);
  68486. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68487. distToJoint = jointPivot.length();
  68488. }
  68489. if (distToJoint !== undefined && distToJoint !== null) {
  68490. pos.x += boneDir.x * distToJoint;
  68491. pos.y += boneDir.y * distToJoint;
  68492. pos.z += boneDir.z * distToJoint;
  68493. }
  68494. mesh.setAbsolutePosition(pos);
  68495. };
  68496. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68497. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68498. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68499. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68500. //Impostor types
  68501. PhysicsImpostor.NoImpostor = 0;
  68502. PhysicsImpostor.SphereImpostor = 1;
  68503. PhysicsImpostor.BoxImpostor = 2;
  68504. PhysicsImpostor.PlaneImpostor = 3;
  68505. PhysicsImpostor.MeshImpostor = 4;
  68506. PhysicsImpostor.CylinderImpostor = 7;
  68507. PhysicsImpostor.ParticleImpostor = 8;
  68508. PhysicsImpostor.HeightmapImpostor = 9;
  68509. return PhysicsImpostor;
  68510. }());
  68511. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68512. })(BABYLON || (BABYLON = {}));
  68513. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68514. var BABYLON;
  68515. (function (BABYLON) {
  68516. var PhysicsEngine = /** @class */ (function () {
  68517. function PhysicsEngine(gravity, _physicsPlugin) {
  68518. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68519. this._physicsPlugin = _physicsPlugin;
  68520. //new methods and parameters
  68521. this._impostors = [];
  68522. this._joints = [];
  68523. if (!this._physicsPlugin.isSupported()) {
  68524. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68525. + "Please make sure it is included.");
  68526. }
  68527. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68528. this.setGravity(gravity);
  68529. this.setTimeStep();
  68530. }
  68531. PhysicsEngine.prototype.setGravity = function (gravity) {
  68532. this.gravity = gravity;
  68533. this._physicsPlugin.setGravity(this.gravity);
  68534. };
  68535. /**
  68536. * Set the time step of the physics engine.
  68537. * default is 1/60.
  68538. * To slow it down, enter 1/600 for example.
  68539. * To speed it up, 1/30
  68540. * @param {number} newTimeStep the new timestep to apply to this world.
  68541. */
  68542. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68543. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68544. this._physicsPlugin.setTimeStep(newTimeStep);
  68545. };
  68546. /**
  68547. * Get the time step of the physics engine.
  68548. */
  68549. PhysicsEngine.prototype.getTimeStep = function () {
  68550. return this._physicsPlugin.getTimeStep();
  68551. };
  68552. PhysicsEngine.prototype.dispose = function () {
  68553. this._impostors.forEach(function (impostor) {
  68554. impostor.dispose();
  68555. });
  68556. this._physicsPlugin.dispose();
  68557. };
  68558. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68559. return this._physicsPlugin.name;
  68560. };
  68561. /**
  68562. * Adding a new impostor for the impostor tracking.
  68563. * This will be done by the impostor itself.
  68564. * @param {PhysicsImpostor} impostor the impostor to add
  68565. */
  68566. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68567. impostor.uniqueId = this._impostors.push(impostor);
  68568. //if no parent, generate the body
  68569. if (!impostor.parent) {
  68570. this._physicsPlugin.generatePhysicsBody(impostor);
  68571. }
  68572. };
  68573. /**
  68574. * Remove an impostor from the engine.
  68575. * This impostor and its mesh will not longer be updated by the physics engine.
  68576. * @param {PhysicsImpostor} impostor the impostor to remove
  68577. */
  68578. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68579. var index = this._impostors.indexOf(impostor);
  68580. if (index > -1) {
  68581. var removed = this._impostors.splice(index, 1);
  68582. //Is it needed?
  68583. if (removed.length) {
  68584. //this will also remove it from the world.
  68585. removed[0].physicsBody = null;
  68586. }
  68587. }
  68588. };
  68589. /**
  68590. * Add a joint to the physics engine
  68591. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68592. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68593. * @param {PhysicsJoint} the joint that will connect both impostors.
  68594. */
  68595. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68596. var impostorJoint = {
  68597. mainImpostor: mainImpostor,
  68598. connectedImpostor: connectedImpostor,
  68599. joint: joint
  68600. };
  68601. joint.physicsPlugin = this._physicsPlugin;
  68602. this._joints.push(impostorJoint);
  68603. this._physicsPlugin.generateJoint(impostorJoint);
  68604. };
  68605. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68606. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68607. return (impostorJoint.connectedImpostor === connectedImpostor
  68608. && impostorJoint.joint === joint
  68609. && impostorJoint.mainImpostor === mainImpostor);
  68610. });
  68611. if (matchingJoints.length) {
  68612. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68613. //TODO remove it from the list as well
  68614. }
  68615. };
  68616. /**
  68617. * Called by the scene. no need to call it.
  68618. */
  68619. PhysicsEngine.prototype._step = function (delta) {
  68620. var _this = this;
  68621. //check if any mesh has no body / requires an update
  68622. this._impostors.forEach(function (impostor) {
  68623. if (impostor.isBodyInitRequired()) {
  68624. _this._physicsPlugin.generatePhysicsBody(impostor);
  68625. }
  68626. });
  68627. if (delta > 0.1) {
  68628. delta = 0.1;
  68629. }
  68630. else if (delta <= 0) {
  68631. delta = 1.0 / 60.0;
  68632. }
  68633. this._physicsPlugin.executeStep(delta, this._impostors);
  68634. };
  68635. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68636. return this._physicsPlugin;
  68637. };
  68638. PhysicsEngine.prototype.getImpostors = function () {
  68639. return this._impostors;
  68640. };
  68641. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68642. for (var i = 0; i < this._impostors.length; ++i) {
  68643. if (this._impostors[i].object === object) {
  68644. return this._impostors[i];
  68645. }
  68646. }
  68647. return null;
  68648. };
  68649. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68650. for (var i = 0; i < this._impostors.length; ++i) {
  68651. if (this._impostors[i].physicsBody === body) {
  68652. return this._impostors[i];
  68653. }
  68654. }
  68655. return null;
  68656. };
  68657. // Statics
  68658. PhysicsEngine.Epsilon = 0.001;
  68659. return PhysicsEngine;
  68660. }());
  68661. BABYLON.PhysicsEngine = PhysicsEngine;
  68662. })(BABYLON || (BABYLON = {}));
  68663. //# sourceMappingURL=babylon.physicsEngine.js.map
  68664. var BABYLON;
  68665. (function (BABYLON) {
  68666. var PhysicsHelper = /** @class */ (function () {
  68667. function PhysicsHelper(scene) {
  68668. this._scene = scene;
  68669. this._physicsEngine = this._scene.getPhysicsEngine();
  68670. if (!this._physicsEngine) {
  68671. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68672. }
  68673. }
  68674. /**
  68675. * @param {Vector3} origin the origin of the explosion
  68676. * @param {number} radius the explosion radius
  68677. * @param {number} strength the explosion strength
  68678. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68679. */
  68680. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68681. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68682. if (!this._physicsEngine) {
  68683. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68684. return null;
  68685. }
  68686. var impostors = this._physicsEngine.getImpostors();
  68687. if (impostors.length === 0) {
  68688. return null;
  68689. }
  68690. var event = new PhysicsRadialExplosionEvent(this._scene);
  68691. impostors.forEach(function (impostor) {
  68692. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68693. if (!impostorForceAndContactPoint) {
  68694. return;
  68695. }
  68696. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68697. });
  68698. event.dispose(false);
  68699. return event;
  68700. };
  68701. /**
  68702. * @param {Vector3} origin the origin of the explosion
  68703. * @param {number} radius the explosion radius
  68704. * @param {number} strength the explosion strength
  68705. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68706. */
  68707. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68708. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68709. if (!this._physicsEngine) {
  68710. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68711. return null;
  68712. }
  68713. var impostors = this._physicsEngine.getImpostors();
  68714. if (impostors.length === 0) {
  68715. return null;
  68716. }
  68717. var event = new PhysicsRadialExplosionEvent(this._scene);
  68718. impostors.forEach(function (impostor) {
  68719. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68720. if (!impostorForceAndContactPoint) {
  68721. return;
  68722. }
  68723. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68724. });
  68725. event.dispose(false);
  68726. return event;
  68727. };
  68728. /**
  68729. * @param {Vector3} origin the origin of the explosion
  68730. * @param {number} radius the explosion radius
  68731. * @param {number} strength the explosion strength
  68732. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68733. */
  68734. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68735. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68736. if (!this._physicsEngine) {
  68737. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68738. return null;
  68739. }
  68740. var impostors = this._physicsEngine.getImpostors();
  68741. if (impostors.length === 0) {
  68742. return null;
  68743. }
  68744. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68745. event.dispose(false);
  68746. return event;
  68747. };
  68748. /**
  68749. * @param {Vector3} origin the origin of the updraft
  68750. * @param {number} radius the radius of the updraft
  68751. * @param {number} strength the strength of the updraft
  68752. * @param {number} height the height of the updraft
  68753. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68754. */
  68755. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68756. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68757. if (!this._physicsEngine) {
  68758. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68759. return null;
  68760. }
  68761. if (this._physicsEngine.getImpostors().length === 0) {
  68762. return null;
  68763. }
  68764. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68765. event.dispose(false);
  68766. return event;
  68767. };
  68768. /**
  68769. * @param {Vector3} origin the of the vortex
  68770. * @param {number} radius the radius of the vortex
  68771. * @param {number} strength the strength of the vortex
  68772. * @param {number} height the height of the vortex
  68773. */
  68774. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68775. if (!this._physicsEngine) {
  68776. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68777. return null;
  68778. }
  68779. if (this._physicsEngine.getImpostors().length === 0) {
  68780. return null;
  68781. }
  68782. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68783. event.dispose(false);
  68784. return event;
  68785. };
  68786. return PhysicsHelper;
  68787. }());
  68788. BABYLON.PhysicsHelper = PhysicsHelper;
  68789. /***** Radial explosion *****/
  68790. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68791. function PhysicsRadialExplosionEvent(scene) {
  68792. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68793. this._rays = [];
  68794. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68795. this._scene = scene;
  68796. }
  68797. /**
  68798. * Returns the data related to the radial explosion event (sphere & rays).
  68799. * @returns {PhysicsRadialExplosionEventData}
  68800. */
  68801. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68802. this._dataFetched = true;
  68803. return {
  68804. sphere: this._sphere,
  68805. rays: this._rays,
  68806. };
  68807. };
  68808. /**
  68809. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68810. * @param impostor
  68811. * @param {Vector3} origin the origin of the explosion
  68812. * @param {number} radius the explosion radius
  68813. * @param {number} strength the explosion strength
  68814. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68815. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68816. */
  68817. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68818. if (impostor.mass === 0) {
  68819. return null;
  68820. }
  68821. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68822. return null;
  68823. }
  68824. if (impostor.object.getClassName() !== 'Mesh') {
  68825. return null;
  68826. }
  68827. var impostorObject = impostor.object;
  68828. var impostorObjectCenter = impostor.getObjectCenter();
  68829. var direction = impostorObjectCenter.subtract(origin);
  68830. var ray = new BABYLON.Ray(origin, direction, radius);
  68831. this._rays.push(ray);
  68832. var hit = ray.intersectsMesh(impostorObject);
  68833. var contactPoint = hit.pickedPoint;
  68834. if (!contactPoint) {
  68835. return null;
  68836. }
  68837. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68838. if (distanceFromOrigin > radius) {
  68839. return null;
  68840. }
  68841. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68842. ? strength
  68843. : strength * (1 - (distanceFromOrigin / radius));
  68844. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68845. return { force: force, contactPoint: contactPoint };
  68846. };
  68847. /**
  68848. * Disposes the sphere.
  68849. * @param {bolean} force
  68850. */
  68851. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68852. var _this = this;
  68853. if (force === void 0) { force = true; }
  68854. if (force) {
  68855. this._sphere.dispose();
  68856. }
  68857. else {
  68858. setTimeout(function () {
  68859. if (!_this._dataFetched) {
  68860. _this._sphere.dispose();
  68861. }
  68862. }, 0);
  68863. }
  68864. };
  68865. /*** Helpers ***/
  68866. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68867. if (!this._sphere) {
  68868. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68869. this._sphere.isVisible = false;
  68870. }
  68871. };
  68872. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68873. var impostorObject = impostor.object;
  68874. this._prepareSphere();
  68875. this._sphere.position = origin;
  68876. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68877. this._sphere._updateBoundingInfo();
  68878. this._sphere.computeWorldMatrix(true);
  68879. return this._sphere.intersectsMesh(impostorObject, true);
  68880. };
  68881. return PhysicsRadialExplosionEvent;
  68882. }());
  68883. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68884. /***** Gravitational Field *****/
  68885. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68886. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68887. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68888. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68889. this._physicsHelper = physicsHelper;
  68890. this._scene = scene;
  68891. this._origin = origin;
  68892. this._radius = radius;
  68893. this._strength = strength;
  68894. this._falloff = falloff;
  68895. this._tickCallback = this._tick.bind(this);
  68896. }
  68897. /**
  68898. * Returns the data related to the gravitational field event (sphere).
  68899. * @returns {PhysicsGravitationalFieldEventData}
  68900. */
  68901. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68902. this._dataFetched = true;
  68903. return {
  68904. sphere: this._sphere,
  68905. };
  68906. };
  68907. /**
  68908. * Enables the gravitational field.
  68909. */
  68910. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68911. this._tickCallback.call(this);
  68912. this._scene.registerBeforeRender(this._tickCallback);
  68913. };
  68914. /**
  68915. * Disables the gravitational field.
  68916. */
  68917. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68918. this._scene.unregisterBeforeRender(this._tickCallback);
  68919. };
  68920. /**
  68921. * Disposes the sphere.
  68922. * @param {bolean} force
  68923. */
  68924. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68925. var _this = this;
  68926. if (force === void 0) { force = true; }
  68927. if (force) {
  68928. this._sphere.dispose();
  68929. }
  68930. else {
  68931. setTimeout(function () {
  68932. if (!_this._dataFetched) {
  68933. _this._sphere.dispose();
  68934. }
  68935. }, 0);
  68936. }
  68937. };
  68938. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68939. // Since the params won't change, we fetch the event only once
  68940. if (this._sphere) {
  68941. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68942. }
  68943. else {
  68944. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68945. if (radialExplosionEvent) {
  68946. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68947. }
  68948. }
  68949. };
  68950. return PhysicsGravitationalFieldEvent;
  68951. }());
  68952. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68953. /***** Updraft *****/
  68954. var PhysicsUpdraftEvent = /** @class */ (function () {
  68955. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68956. this._scene = _scene;
  68957. this._origin = _origin;
  68958. this._radius = _radius;
  68959. this._strength = _strength;
  68960. this._height = _height;
  68961. this._updraftMode = _updraftMode;
  68962. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68963. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68964. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68965. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68966. this._physicsEngine = this._scene.getPhysicsEngine();
  68967. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68968. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68969. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68970. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68971. }
  68972. this._tickCallback = this._tick.bind(this);
  68973. }
  68974. /**
  68975. * Returns the data related to the updraft event (cylinder).
  68976. * @returns {PhysicsUpdraftEventData}
  68977. */
  68978. PhysicsUpdraftEvent.prototype.getData = function () {
  68979. this._dataFetched = true;
  68980. return {
  68981. cylinder: this._cylinder,
  68982. };
  68983. };
  68984. /**
  68985. * Enables the updraft.
  68986. */
  68987. PhysicsUpdraftEvent.prototype.enable = function () {
  68988. this._tickCallback.call(this);
  68989. this._scene.registerBeforeRender(this._tickCallback);
  68990. };
  68991. /**
  68992. * Disables the cortex.
  68993. */
  68994. PhysicsUpdraftEvent.prototype.disable = function () {
  68995. this._scene.unregisterBeforeRender(this._tickCallback);
  68996. };
  68997. /**
  68998. * Disposes the sphere.
  68999. * @param {bolean} force
  69000. */
  69001. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  69002. var _this = this;
  69003. if (force === void 0) { force = true; }
  69004. if (force) {
  69005. this._cylinder.dispose();
  69006. }
  69007. else {
  69008. setTimeout(function () {
  69009. if (!_this._dataFetched) {
  69010. _this._cylinder.dispose();
  69011. }
  69012. }, 0);
  69013. }
  69014. };
  69015. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69016. if (impostor.mass === 0) {
  69017. return null;
  69018. }
  69019. if (!this._intersectsWithCylinder(impostor)) {
  69020. return null;
  69021. }
  69022. var impostorObjectCenter = impostor.getObjectCenter();
  69023. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69024. var direction = this._originDirection;
  69025. }
  69026. else {
  69027. var direction = impostorObjectCenter.subtract(this._originTop);
  69028. }
  69029. var multiplier = this._strength * -1;
  69030. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69031. return { force: force, contactPoint: impostorObjectCenter };
  69032. };
  69033. PhysicsUpdraftEvent.prototype._tick = function () {
  69034. var _this = this;
  69035. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69036. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69037. if (!impostorForceAndContactPoint) {
  69038. return;
  69039. }
  69040. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69041. });
  69042. };
  69043. /*** Helpers ***/
  69044. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69045. if (!this._cylinder) {
  69046. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69047. height: this._height,
  69048. diameter: this._radius * 2,
  69049. }, this._scene);
  69050. this._cylinder.isVisible = false;
  69051. }
  69052. };
  69053. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69054. var impostorObject = impostor.object;
  69055. this._prepareCylinder();
  69056. this._cylinder.position = this._cylinderPosition;
  69057. return this._cylinder.intersectsMesh(impostorObject, true);
  69058. };
  69059. return PhysicsUpdraftEvent;
  69060. }());
  69061. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69062. /***** Vortex *****/
  69063. var PhysicsVortexEvent = /** @class */ (function () {
  69064. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69065. this._scene = _scene;
  69066. this._origin = _origin;
  69067. this._radius = _radius;
  69068. this._strength = _strength;
  69069. this._height = _height;
  69070. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69071. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69072. this._updraftMultiplier = 0.02;
  69073. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69074. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69075. this._physicsEngine = this._scene.getPhysicsEngine();
  69076. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69077. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69078. this._tickCallback = this._tick.bind(this);
  69079. }
  69080. /**
  69081. * Returns the data related to the vortex event (cylinder).
  69082. * @returns {PhysicsVortexEventData}
  69083. */
  69084. PhysicsVortexEvent.prototype.getData = function () {
  69085. this._dataFetched = true;
  69086. return {
  69087. cylinder: this._cylinder,
  69088. };
  69089. };
  69090. /**
  69091. * Enables the vortex.
  69092. */
  69093. PhysicsVortexEvent.prototype.enable = function () {
  69094. this._tickCallback.call(this);
  69095. this._scene.registerBeforeRender(this._tickCallback);
  69096. };
  69097. /**
  69098. * Disables the cortex.
  69099. */
  69100. PhysicsVortexEvent.prototype.disable = function () {
  69101. this._scene.unregisterBeforeRender(this._tickCallback);
  69102. };
  69103. /**
  69104. * Disposes the sphere.
  69105. * @param {bolean} force
  69106. */
  69107. PhysicsVortexEvent.prototype.dispose = function (force) {
  69108. var _this = this;
  69109. if (force === void 0) { force = true; }
  69110. if (force) {
  69111. this._cylinder.dispose();
  69112. }
  69113. else {
  69114. setTimeout(function () {
  69115. if (!_this._dataFetched) {
  69116. _this._cylinder.dispose();
  69117. }
  69118. }, 0);
  69119. }
  69120. };
  69121. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69122. if (impostor.mass === 0) {
  69123. return null;
  69124. }
  69125. if (!this._intersectsWithCylinder(impostor)) {
  69126. return null;
  69127. }
  69128. if (impostor.object.getClassName() !== 'Mesh') {
  69129. return null;
  69130. }
  69131. var impostorObject = impostor.object;
  69132. var impostorObjectCenter = impostor.getObjectCenter();
  69133. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  69134. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69135. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69136. var hit = ray.intersectsMesh(impostorObject);
  69137. var contactPoint = hit.pickedPoint;
  69138. if (!contactPoint) {
  69139. return null;
  69140. }
  69141. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69142. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69143. var directionToOrigin = contactPoint.normalize();
  69144. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69145. directionToOrigin = directionToOrigin.negate();
  69146. }
  69147. // TODO: find a more physically based solution
  69148. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69149. var forceX = directionToOrigin.x * this._strength / 8;
  69150. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69151. var forceZ = directionToOrigin.z * this._strength / 8;
  69152. }
  69153. else {
  69154. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69155. var forceY = this._originTop.y * this._updraftMultiplier;
  69156. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69157. }
  69158. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69159. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69160. return { force: force, contactPoint: impostorObjectCenter };
  69161. };
  69162. PhysicsVortexEvent.prototype._tick = function () {
  69163. var _this = this;
  69164. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69165. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69166. if (!impostorForceAndContactPoint) {
  69167. return;
  69168. }
  69169. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69170. });
  69171. };
  69172. /*** Helpers ***/
  69173. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69174. if (!this._cylinder) {
  69175. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69176. height: this._height,
  69177. diameter: this._radius * 2,
  69178. }, this._scene);
  69179. this._cylinder.isVisible = false;
  69180. }
  69181. };
  69182. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69183. var impostorObject = impostor.object;
  69184. this._prepareCylinder();
  69185. this._cylinder.position = this._cylinderPosition;
  69186. return this._cylinder.intersectsMesh(impostorObject, true);
  69187. };
  69188. return PhysicsVortexEvent;
  69189. }());
  69190. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69191. /***** Enums *****/
  69192. /**
  69193. * The strenght of the force in correspondence to the distance of the affected object
  69194. */
  69195. var PhysicsRadialImpulseFalloff;
  69196. (function (PhysicsRadialImpulseFalloff) {
  69197. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69198. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69199. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69200. /**
  69201. * The strenght of the force in correspondence to the distance of the affected object
  69202. */
  69203. var PhysicsUpdraftMode;
  69204. (function (PhysicsUpdraftMode) {
  69205. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69206. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69207. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69208. })(BABYLON || (BABYLON = {}));
  69209. //# sourceMappingURL=babylon.physicsHelper.js.map
  69210. var BABYLON;
  69211. (function (BABYLON) {
  69212. var CannonJSPlugin = /** @class */ (function () {
  69213. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69214. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69215. if (iterations === void 0) { iterations = 10; }
  69216. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69217. this.name = "CannonJSPlugin";
  69218. this._physicsMaterials = new Array();
  69219. this._fixedTimeStep = 1 / 60;
  69220. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69221. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69222. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69223. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69224. this._tmpPosition = BABYLON.Vector3.Zero();
  69225. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69226. this._tmpUnityRotation = new BABYLON.Quaternion();
  69227. if (!this.isSupported()) {
  69228. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69229. return;
  69230. }
  69231. this._extendNamespace();
  69232. this.world = new this.BJSCANNON.World();
  69233. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69234. this.world.solver.iterations = iterations;
  69235. }
  69236. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69237. this.world.gravity.copy(gravity);
  69238. };
  69239. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69240. this._fixedTimeStep = timeStep;
  69241. };
  69242. CannonJSPlugin.prototype.getTimeStep = function () {
  69243. return this._fixedTimeStep;
  69244. };
  69245. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69246. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69247. };
  69248. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69249. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69250. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69251. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69252. };
  69253. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69254. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69255. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69256. impostor.physicsBody.applyForce(impulse, worldPoint);
  69257. };
  69258. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69259. //parent-child relationship. Does this impostor has a parent impostor?
  69260. if (impostor.parent) {
  69261. if (impostor.physicsBody) {
  69262. this.removePhysicsBody(impostor);
  69263. //TODO is that needed?
  69264. impostor.forceUpdate();
  69265. }
  69266. return;
  69267. }
  69268. //should a new body be created for this impostor?
  69269. if (impostor.isBodyInitRequired()) {
  69270. var shape = this._createShape(impostor);
  69271. //unregister events, if body is being changed
  69272. var oldBody = impostor.physicsBody;
  69273. if (oldBody) {
  69274. this.removePhysicsBody(impostor);
  69275. }
  69276. //create the body and material
  69277. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69278. var bodyCreationObject = {
  69279. mass: impostor.getParam("mass"),
  69280. material: material
  69281. };
  69282. // A simple extend, in case native options were used.
  69283. var nativeOptions = impostor.getParam("nativeOptions");
  69284. for (var key in nativeOptions) {
  69285. if (nativeOptions.hasOwnProperty(key)) {
  69286. bodyCreationObject[key] = nativeOptions[key];
  69287. }
  69288. }
  69289. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69290. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69291. this.world.addEventListener("preStep", impostor.beforeStep);
  69292. this.world.addEventListener("postStep", impostor.afterStep);
  69293. impostor.physicsBody.addShape(shape);
  69294. this.world.add(impostor.physicsBody);
  69295. //try to keep the body moving in the right direction by taking old properties.
  69296. //Should be tested!
  69297. if (oldBody) {
  69298. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69299. impostor.physicsBody[param].copy(oldBody[param]);
  69300. });
  69301. }
  69302. this._processChildMeshes(impostor);
  69303. }
  69304. //now update the body's transformation
  69305. this._updatePhysicsBodyTransformation(impostor);
  69306. };
  69307. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69308. var _this = this;
  69309. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69310. var currentRotation = mainImpostor.object.rotationQuaternion;
  69311. if (meshChildren.length) {
  69312. var processMesh = function (localPosition, mesh) {
  69313. if (!currentRotation || !mesh.rotationQuaternion) {
  69314. return;
  69315. }
  69316. var childImpostor = mesh.getPhysicsImpostor();
  69317. if (childImpostor) {
  69318. var parent = childImpostor.parent;
  69319. if (parent !== mainImpostor) {
  69320. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69321. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69322. if (childImpostor.physicsBody) {
  69323. _this.removePhysicsBody(childImpostor);
  69324. childImpostor.physicsBody = null;
  69325. }
  69326. childImpostor.parent = mainImpostor;
  69327. childImpostor.resetUpdateFlags();
  69328. 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));
  69329. //Add the mass of the children.
  69330. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69331. }
  69332. }
  69333. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69334. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69335. };
  69336. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69337. }
  69338. };
  69339. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69340. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69341. this.world.removeEventListener("preStep", impostor.beforeStep);
  69342. this.world.removeEventListener("postStep", impostor.afterStep);
  69343. this.world.remove(impostor.physicsBody);
  69344. };
  69345. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69346. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69347. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69348. if (!mainBody || !connectedBody) {
  69349. return;
  69350. }
  69351. var constraint;
  69352. var jointData = impostorJoint.joint.jointData;
  69353. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69354. var constraintData = {
  69355. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69356. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69357. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69358. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69359. maxForce: jointData.nativeParams.maxForce,
  69360. collideConnected: !!jointData.collision
  69361. };
  69362. switch (impostorJoint.joint.type) {
  69363. case BABYLON.PhysicsJoint.HingeJoint:
  69364. case BABYLON.PhysicsJoint.Hinge2Joint:
  69365. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69366. break;
  69367. case BABYLON.PhysicsJoint.DistanceJoint:
  69368. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69369. break;
  69370. case BABYLON.PhysicsJoint.SpringJoint:
  69371. var springData = jointData;
  69372. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69373. restLength: springData.length,
  69374. stiffness: springData.stiffness,
  69375. damping: springData.damping,
  69376. localAnchorA: constraintData.pivotA,
  69377. localAnchorB: constraintData.pivotB
  69378. });
  69379. break;
  69380. case BABYLON.PhysicsJoint.LockJoint:
  69381. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69382. break;
  69383. case BABYLON.PhysicsJoint.PointToPointJoint:
  69384. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69385. default:
  69386. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69387. break;
  69388. }
  69389. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69390. constraint.collideConnected = !!jointData.collision;
  69391. impostorJoint.joint.physicsJoint = constraint;
  69392. //don't add spring as constraint, as it is not one.
  69393. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69394. this.world.addConstraint(constraint);
  69395. }
  69396. else {
  69397. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69398. constraint.applyForce();
  69399. });
  69400. }
  69401. };
  69402. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69403. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69404. };
  69405. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69406. var index;
  69407. var mat;
  69408. for (index = 0; index < this._physicsMaterials.length; index++) {
  69409. mat = this._physicsMaterials[index];
  69410. if (mat.friction === friction && mat.restitution === restitution) {
  69411. return mat;
  69412. }
  69413. }
  69414. var currentMat = new this.BJSCANNON.Material(name);
  69415. currentMat.friction = friction;
  69416. currentMat.restitution = restitution;
  69417. this._physicsMaterials.push(currentMat);
  69418. return currentMat;
  69419. };
  69420. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69421. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69422. };
  69423. CannonJSPlugin.prototype._createShape = function (impostor) {
  69424. var object = impostor.object;
  69425. var returnValue;
  69426. var extendSize = impostor.getObjectExtendSize();
  69427. switch (impostor.type) {
  69428. case BABYLON.PhysicsImpostor.SphereImpostor:
  69429. var radiusX = extendSize.x;
  69430. var radiusY = extendSize.y;
  69431. var radiusZ = extendSize.z;
  69432. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69433. break;
  69434. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69435. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69436. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69437. break;
  69438. case BABYLON.PhysicsImpostor.BoxImpostor:
  69439. var box = extendSize.scale(0.5);
  69440. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69441. break;
  69442. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69443. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69444. returnValue = new this.BJSCANNON.Plane();
  69445. break;
  69446. case BABYLON.PhysicsImpostor.MeshImpostor:
  69447. // should transform the vertex data to world coordinates!!
  69448. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69449. var rawFaces = object.getIndices ? object.getIndices() : [];
  69450. if (!rawVerts)
  69451. return;
  69452. // get only scale! so the object could transform correctly.
  69453. var oldPosition = object.position.clone();
  69454. var oldRotation = object.rotation && object.rotation.clone();
  69455. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69456. object.position.copyFromFloats(0, 0, 0);
  69457. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69458. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69459. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69460. var transform = object.computeWorldMatrix(true);
  69461. // convert rawVerts to object space
  69462. var temp = new Array();
  69463. var index;
  69464. for (index = 0; index < rawVerts.length; index += 3) {
  69465. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69466. }
  69467. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69468. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69469. //now set back the transformation!
  69470. object.position.copyFrom(oldPosition);
  69471. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69472. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69473. break;
  69474. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69475. var oldPosition2 = object.position.clone();
  69476. var oldRotation2 = object.rotation && object.rotation.clone();
  69477. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69478. object.position.copyFromFloats(0, 0, 0);
  69479. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69480. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69481. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69482. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69483. returnValue = this._createHeightmap(object);
  69484. object.position.copyFrom(oldPosition2);
  69485. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69486. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69487. object.computeWorldMatrix(true);
  69488. break;
  69489. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69490. returnValue = new this.BJSCANNON.Particle();
  69491. break;
  69492. }
  69493. return returnValue;
  69494. };
  69495. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69496. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69497. var transform = object.computeWorldMatrix(true);
  69498. // convert rawVerts to object space
  69499. var temp = new Array();
  69500. var index;
  69501. for (index = 0; index < pos.length; index += 3) {
  69502. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69503. }
  69504. pos = temp;
  69505. var matrix = new Array();
  69506. //For now pointDepth will not be used and will be automatically calculated.
  69507. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69508. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69509. var boundingInfo = object.getBoundingInfo();
  69510. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69511. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69512. var elementSize = dim * 2 / arraySize;
  69513. for (var i = 0; i < pos.length; i = i + 3) {
  69514. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69515. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69516. var y = -pos[i + 2] + minY;
  69517. if (!matrix[x]) {
  69518. matrix[x] = [];
  69519. }
  69520. if (!matrix[x][z]) {
  69521. matrix[x][z] = y;
  69522. }
  69523. matrix[x][z] = Math.max(y, matrix[x][z]);
  69524. }
  69525. for (var x = 0; x <= arraySize; ++x) {
  69526. if (!matrix[x]) {
  69527. var loc = 1;
  69528. while (!matrix[(x + loc) % arraySize]) {
  69529. loc++;
  69530. }
  69531. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69532. //console.log("missing x", x);
  69533. }
  69534. for (var z = 0; z <= arraySize; ++z) {
  69535. if (!matrix[x][z]) {
  69536. var loc = 1;
  69537. var newValue;
  69538. while (newValue === undefined) {
  69539. newValue = matrix[x][(z + loc++) % arraySize];
  69540. }
  69541. matrix[x][z] = newValue;
  69542. }
  69543. }
  69544. }
  69545. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69546. elementSize: elementSize
  69547. });
  69548. //For future reference, needed for body transformation
  69549. shape.minY = minY;
  69550. return shape;
  69551. };
  69552. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69553. var object = impostor.object;
  69554. //make sure it is updated...
  69555. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69556. // The delta between the mesh position and the mesh bounding box center
  69557. var bInfo = object.getBoundingInfo();
  69558. if (!bInfo)
  69559. return;
  69560. var center = impostor.getObjectCenter();
  69561. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69562. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69563. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69564. this._tmpPosition.copyFrom(center);
  69565. var quaternion = object.rotationQuaternion;
  69566. if (!quaternion) {
  69567. return;
  69568. }
  69569. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69570. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69571. //-90 DEG in X, precalculated
  69572. quaternion = quaternion.multiply(this._minus90X);
  69573. //Invert! (Precalculated, 90 deg in X)
  69574. //No need to clone. this will never change.
  69575. impostor.setDeltaRotation(this._plus90X);
  69576. }
  69577. //If it is a heightfield, if should be centered.
  69578. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69579. var mesh = object;
  69580. var boundingInfo = mesh.getBoundingInfo();
  69581. //calculate the correct body position:
  69582. var rotationQuaternion = mesh.rotationQuaternion;
  69583. mesh.rotationQuaternion = this._tmpUnityRotation;
  69584. mesh.computeWorldMatrix(true);
  69585. //get original center with no rotation
  69586. var c = center.clone();
  69587. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69588. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69589. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69590. mesh.setPivotMatrix(p);
  69591. mesh.computeWorldMatrix(true);
  69592. //calculate the translation
  69593. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69594. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69595. //add it inverted to the delta
  69596. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69597. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69598. //rotation is back
  69599. mesh.rotationQuaternion = rotationQuaternion;
  69600. mesh.setPivotMatrix(oldPivot);
  69601. mesh.computeWorldMatrix(true);
  69602. }
  69603. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69604. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69605. //this._tmpPosition.copyFrom(object.position);
  69606. }
  69607. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69608. //Now update the impostor object
  69609. impostor.physicsBody.position.copy(this._tmpPosition);
  69610. impostor.physicsBody.quaternion.copy(quaternion);
  69611. };
  69612. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69613. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69614. if (impostor.object.rotationQuaternion) {
  69615. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69616. }
  69617. };
  69618. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69619. impostor.physicsBody.position.copy(newPosition);
  69620. impostor.physicsBody.quaternion.copy(newRotation);
  69621. };
  69622. CannonJSPlugin.prototype.isSupported = function () {
  69623. return this.BJSCANNON !== undefined;
  69624. };
  69625. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69626. impostor.physicsBody.velocity.copy(velocity);
  69627. };
  69628. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69629. impostor.physicsBody.angularVelocity.copy(velocity);
  69630. };
  69631. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69632. var v = impostor.physicsBody.velocity;
  69633. if (!v) {
  69634. return null;
  69635. }
  69636. return new BABYLON.Vector3(v.x, v.y, v.z);
  69637. };
  69638. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69639. var v = impostor.physicsBody.angularVelocity;
  69640. if (!v) {
  69641. return null;
  69642. }
  69643. return new BABYLON.Vector3(v.x, v.y, v.z);
  69644. };
  69645. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69646. impostor.physicsBody.mass = mass;
  69647. impostor.physicsBody.updateMassProperties();
  69648. };
  69649. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69650. return impostor.physicsBody.mass;
  69651. };
  69652. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69653. return impostor.physicsBody.material.friction;
  69654. };
  69655. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69656. impostor.physicsBody.material.friction = friction;
  69657. };
  69658. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69659. return impostor.physicsBody.material.restitution;
  69660. };
  69661. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69662. impostor.physicsBody.material.restitution = restitution;
  69663. };
  69664. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69665. impostor.physicsBody.sleep();
  69666. };
  69667. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69668. impostor.physicsBody.wakeUp();
  69669. };
  69670. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69671. joint.physicsJoint.distance = maxDistance;
  69672. };
  69673. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69674. // if (!motorIndex) {
  69675. // joint.physicsJoint.enableMotor();
  69676. // }
  69677. // }
  69678. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69679. // if (!motorIndex) {
  69680. // joint.physicsJoint.disableMotor();
  69681. // }
  69682. // }
  69683. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69684. if (!motorIndex) {
  69685. joint.physicsJoint.enableMotor();
  69686. joint.physicsJoint.setMotorSpeed(speed);
  69687. if (maxForce) {
  69688. this.setLimit(joint, maxForce);
  69689. }
  69690. }
  69691. };
  69692. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69693. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69694. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69695. };
  69696. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69697. var body = impostor.physicsBody;
  69698. mesh.position.x = body.position.x;
  69699. mesh.position.y = body.position.y;
  69700. mesh.position.z = body.position.z;
  69701. if (mesh.rotationQuaternion) {
  69702. mesh.rotationQuaternion.x = body.quaternion.x;
  69703. mesh.rotationQuaternion.y = body.quaternion.y;
  69704. mesh.rotationQuaternion.z = body.quaternion.z;
  69705. mesh.rotationQuaternion.w = body.quaternion.w;
  69706. }
  69707. };
  69708. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69709. var shape = impostor.physicsBody.shapes[0];
  69710. return shape.boundingSphereRadius;
  69711. };
  69712. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69713. var shape = impostor.physicsBody.shapes[0];
  69714. result.x = shape.halfExtents.x * 2;
  69715. result.y = shape.halfExtents.y * 2;
  69716. result.z = shape.halfExtents.z * 2;
  69717. };
  69718. CannonJSPlugin.prototype.dispose = function () {
  69719. };
  69720. CannonJSPlugin.prototype._extendNamespace = function () {
  69721. //this will force cannon to execute at least one step when using interpolation
  69722. var step_tmp1 = new this.BJSCANNON.Vec3();
  69723. var Engine = this.BJSCANNON;
  69724. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69725. maxSubSteps = maxSubSteps || 10;
  69726. timeSinceLastCalled = timeSinceLastCalled || 0;
  69727. if (timeSinceLastCalled === 0) {
  69728. this.internalStep(dt);
  69729. this.time += dt;
  69730. }
  69731. else {
  69732. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69733. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69734. var t0 = performance.now();
  69735. for (var i = 0; i !== internalSteps; i++) {
  69736. this.internalStep(dt);
  69737. if (performance.now() - t0 > dt * 1000) {
  69738. break;
  69739. }
  69740. }
  69741. this.time += timeSinceLastCalled;
  69742. var h = this.time % dt;
  69743. var h_div_dt = h / dt;
  69744. var interpvelo = step_tmp1;
  69745. var bodies = this.bodies;
  69746. for (var j = 0; j !== bodies.length; j++) {
  69747. var b = bodies[j];
  69748. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69749. b.position.vsub(b.previousPosition, interpvelo);
  69750. interpvelo.scale(h_div_dt, interpvelo);
  69751. b.position.vadd(interpvelo, b.interpolatedPosition);
  69752. }
  69753. else {
  69754. b.interpolatedPosition.copy(b.position);
  69755. b.interpolatedQuaternion.copy(b.quaternion);
  69756. }
  69757. }
  69758. }
  69759. };
  69760. };
  69761. return CannonJSPlugin;
  69762. }());
  69763. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69764. })(BABYLON || (BABYLON = {}));
  69765. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69766. var BABYLON;
  69767. (function (BABYLON) {
  69768. var OimoJSPlugin = /** @class */ (function () {
  69769. function OimoJSPlugin(iterations) {
  69770. this.name = "OimoJSPlugin";
  69771. this._tmpImpostorsArray = [];
  69772. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69773. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69774. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69775. this.world.worldscale(1);
  69776. this.world.clear();
  69777. //making sure no stats are calculated
  69778. this.world.isNoStat = true;
  69779. }
  69780. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69781. this.world.gravity.copy(gravity);
  69782. };
  69783. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69784. this.world.timeStep = timeStep;
  69785. };
  69786. OimoJSPlugin.prototype.getTimeStep = function () {
  69787. return this.world.timeStep;
  69788. };
  69789. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69790. var _this = this;
  69791. impostors.forEach(function (impostor) {
  69792. impostor.beforeStep();
  69793. });
  69794. this.world.step();
  69795. impostors.forEach(function (impostor) {
  69796. impostor.afterStep();
  69797. //update the ordered impostors array
  69798. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69799. });
  69800. //check for collisions
  69801. var contact = this.world.contacts;
  69802. while (contact !== null) {
  69803. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69804. contact = contact.next;
  69805. continue;
  69806. }
  69807. //is this body colliding with any other? get the impostor
  69808. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69809. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69810. if (!mainImpostor || !collidingImpostor) {
  69811. contact = contact.next;
  69812. continue;
  69813. }
  69814. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69815. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69816. contact = contact.next;
  69817. }
  69818. };
  69819. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69820. var mass = impostor.physicsBody.massInfo.mass;
  69821. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69822. };
  69823. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69824. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69825. this.applyImpulse(impostor, force, contactPoint);
  69826. };
  69827. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69828. var _this = this;
  69829. //parent-child relationship. Does this impostor has a parent impostor?
  69830. if (impostor.parent) {
  69831. if (impostor.physicsBody) {
  69832. this.removePhysicsBody(impostor);
  69833. //TODO is that needed?
  69834. impostor.forceUpdate();
  69835. }
  69836. return;
  69837. }
  69838. if (impostor.isBodyInitRequired()) {
  69839. var bodyConfig = {
  69840. name: impostor.uniqueId,
  69841. //Oimo must have mass, also for static objects.
  69842. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69843. size: [],
  69844. type: [],
  69845. pos: [],
  69846. rot: [],
  69847. move: impostor.getParam("mass") !== 0,
  69848. //Supporting older versions of Oimo
  69849. world: this.world
  69850. };
  69851. var impostors = [impostor];
  69852. var addToArray = function (parent) {
  69853. if (!parent.getChildMeshes)
  69854. return;
  69855. parent.getChildMeshes().forEach(function (m) {
  69856. if (m.physicsImpostor) {
  69857. impostors.push(m.physicsImpostor);
  69858. //m.physicsImpostor._init();
  69859. }
  69860. });
  69861. };
  69862. addToArray(impostor.object);
  69863. var checkWithEpsilon_1 = function (value) {
  69864. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69865. };
  69866. impostors.forEach(function (i) {
  69867. if (!impostor.object.rotationQuaternion) {
  69868. return;
  69869. }
  69870. //get the correct bounding box
  69871. var oldQuaternion = i.object.rotationQuaternion;
  69872. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69873. x: impostor.object.rotationQuaternion.x,
  69874. y: impostor.object.rotationQuaternion.y,
  69875. z: impostor.object.rotationQuaternion.z,
  69876. s: impostor.object.rotationQuaternion.w
  69877. });
  69878. var extendSize = i.getObjectExtendSize();
  69879. if (i === impostor) {
  69880. var center = impostor.getObjectCenter();
  69881. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69882. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69883. //Can also use Array.prototype.push.apply
  69884. bodyConfig.pos.push(center.x);
  69885. bodyConfig.pos.push(center.y);
  69886. bodyConfig.pos.push(center.z);
  69887. //tmp solution
  69888. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69889. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69890. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69891. }
  69892. else {
  69893. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69894. bodyConfig.pos.push(localPosition.x);
  69895. bodyConfig.pos.push(localPosition.y);
  69896. bodyConfig.pos.push(localPosition.z);
  69897. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69898. bodyConfig.rot.push(0);
  69899. bodyConfig.rot.push(0);
  69900. bodyConfig.rot.push(0);
  69901. }
  69902. // register mesh
  69903. switch (i.type) {
  69904. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69905. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69906. case BABYLON.PhysicsImpostor.SphereImpostor:
  69907. var radiusX = extendSize.x;
  69908. var radiusY = extendSize.y;
  69909. var radiusZ = extendSize.z;
  69910. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69911. bodyConfig.type.push('sphere');
  69912. //due to the way oimo works with compounds, add 3 times
  69913. bodyConfig.size.push(size);
  69914. bodyConfig.size.push(size);
  69915. bodyConfig.size.push(size);
  69916. break;
  69917. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69918. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69919. var sizeY = checkWithEpsilon_1(extendSize.y);
  69920. bodyConfig.type.push('cylinder');
  69921. bodyConfig.size.push(sizeX);
  69922. bodyConfig.size.push(sizeY);
  69923. //due to the way oimo works with compounds, add one more value.
  69924. bodyConfig.size.push(sizeY);
  69925. break;
  69926. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69927. case BABYLON.PhysicsImpostor.BoxImpostor:
  69928. default:
  69929. var sizeX = checkWithEpsilon_1(extendSize.x);
  69930. var sizeY = checkWithEpsilon_1(extendSize.y);
  69931. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69932. bodyConfig.type.push('box');
  69933. bodyConfig.size.push(sizeX);
  69934. bodyConfig.size.push(sizeY);
  69935. bodyConfig.size.push(sizeZ);
  69936. break;
  69937. }
  69938. //actually not needed, but hey...
  69939. i.object.rotationQuaternion = oldQuaternion;
  69940. });
  69941. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69942. }
  69943. else {
  69944. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69945. }
  69946. impostor.setDeltaPosition(this._tmpPositionVector);
  69947. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69948. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69949. };
  69950. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69951. //impostor.physicsBody.dispose();
  69952. //Same as : (older oimo versions)
  69953. this.world.removeRigidBody(impostor.physicsBody);
  69954. };
  69955. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69956. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69957. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69958. if (!mainBody || !connectedBody) {
  69959. return;
  69960. }
  69961. var jointData = impostorJoint.joint.jointData;
  69962. var options = jointData.nativeParams || {};
  69963. var type;
  69964. var nativeJointData = {
  69965. body1: mainBody,
  69966. body2: connectedBody,
  69967. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69968. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69969. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69970. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69971. min: options.min,
  69972. max: options.max,
  69973. collision: options.collision || jointData.collision,
  69974. spring: options.spring,
  69975. //supporting older version of Oimo
  69976. world: this.world
  69977. };
  69978. switch (impostorJoint.joint.type) {
  69979. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69980. type = "jointBall";
  69981. break;
  69982. case BABYLON.PhysicsJoint.SpringJoint:
  69983. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69984. var springData = jointData;
  69985. nativeJointData.min = springData.length || nativeJointData.min;
  69986. //Max should also be set, just make sure it is at least min
  69987. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69988. case BABYLON.PhysicsJoint.DistanceJoint:
  69989. type = "jointDistance";
  69990. nativeJointData.max = jointData.maxDistance;
  69991. break;
  69992. case BABYLON.PhysicsJoint.PrismaticJoint:
  69993. type = "jointPrisme";
  69994. break;
  69995. case BABYLON.PhysicsJoint.SliderJoint:
  69996. type = "jointSlide";
  69997. break;
  69998. case BABYLON.PhysicsJoint.WheelJoint:
  69999. type = "jointWheel";
  70000. break;
  70001. case BABYLON.PhysicsJoint.HingeJoint:
  70002. default:
  70003. type = "jointHinge";
  70004. break;
  70005. }
  70006. nativeJointData.type = type;
  70007. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  70008. };
  70009. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  70010. //Bug in Oimo prevents us from disposing a joint in the playground
  70011. //joint.joint.physicsJoint.dispose();
  70012. //So we will bruteforce it!
  70013. try {
  70014. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70015. }
  70016. catch (e) {
  70017. BABYLON.Tools.Warn(e);
  70018. }
  70019. };
  70020. OimoJSPlugin.prototype.isSupported = function () {
  70021. return this.BJSOIMO !== undefined;
  70022. };
  70023. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70024. if (!impostor.physicsBody.sleeping) {
  70025. //TODO check that
  70026. if (impostor.physicsBody.shapes.next) {
  70027. var parentShape = this._getLastShape(impostor.physicsBody);
  70028. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70029. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70030. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70031. }
  70032. else {
  70033. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70034. }
  70035. if (impostor.object.rotationQuaternion) {
  70036. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70037. impostor.object.rotationQuaternion.normalize();
  70038. }
  70039. }
  70040. };
  70041. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70042. var body = impostor.physicsBody;
  70043. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70044. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70045. body.syncShapes();
  70046. body.awake();
  70047. };
  70048. OimoJSPlugin.prototype._getLastShape = function (body) {
  70049. var lastShape = body.shapes;
  70050. while (lastShape.next) {
  70051. lastShape = lastShape.next;
  70052. }
  70053. return lastShape;
  70054. };
  70055. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70056. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70057. };
  70058. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70059. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70060. };
  70061. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70062. var v = impostor.physicsBody.linearVelocity;
  70063. if (!v) {
  70064. return null;
  70065. }
  70066. return new BABYLON.Vector3(v.x, v.y, v.z);
  70067. };
  70068. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70069. var v = impostor.physicsBody.angularVelocity;
  70070. if (!v) {
  70071. return null;
  70072. }
  70073. return new BABYLON.Vector3(v.x, v.y, v.z);
  70074. };
  70075. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70076. var staticBody = mass === 0;
  70077. //this will actually set the body's density and not its mass.
  70078. //But this is how oimo treats the mass variable.
  70079. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70080. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70081. };
  70082. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70083. return impostor.physicsBody.shapes.density;
  70084. };
  70085. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70086. return impostor.physicsBody.shapes.friction;
  70087. };
  70088. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70089. impostor.physicsBody.shapes.friction = friction;
  70090. };
  70091. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70092. return impostor.physicsBody.shapes.restitution;
  70093. };
  70094. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70095. impostor.physicsBody.shapes.restitution = restitution;
  70096. };
  70097. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70098. impostor.physicsBody.sleep();
  70099. };
  70100. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70101. impostor.physicsBody.awake();
  70102. };
  70103. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70104. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70105. if (minDistance !== void 0) {
  70106. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70107. }
  70108. };
  70109. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70110. //TODO separate rotational and transational motors.
  70111. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70112. if (motor) {
  70113. motor.setMotor(speed, maxForce);
  70114. }
  70115. };
  70116. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70117. //TODO separate rotational and transational motors.
  70118. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70119. if (motor) {
  70120. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70121. }
  70122. };
  70123. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70124. var body = impostor.physicsBody;
  70125. mesh.position.x = body.position.x;
  70126. mesh.position.y = body.position.y;
  70127. mesh.position.z = body.position.z;
  70128. if (mesh.rotationQuaternion) {
  70129. mesh.rotationQuaternion.x = body.orientation.x;
  70130. mesh.rotationQuaternion.y = body.orientation.y;
  70131. mesh.rotationQuaternion.z = body.orientation.z;
  70132. mesh.rotationQuaternion.w = body.orientation.s;
  70133. }
  70134. };
  70135. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70136. return impostor.physicsBody.shapes.radius;
  70137. };
  70138. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70139. var shape = impostor.physicsBody.shapes;
  70140. result.x = shape.halfWidth * 2;
  70141. result.y = shape.halfHeight * 2;
  70142. result.z = shape.halfDepth * 2;
  70143. };
  70144. OimoJSPlugin.prototype.dispose = function () {
  70145. this.world.clear();
  70146. };
  70147. return OimoJSPlugin;
  70148. }());
  70149. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70150. })(BABYLON || (BABYLON = {}));
  70151. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70152. var BABYLON;
  70153. (function (BABYLON) {
  70154. /*
  70155. * Based on jsTGALoader - Javascript loader for TGA file
  70156. * By Vincent Thibault
  70157. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70158. */
  70159. var TGATools = /** @class */ (function () {
  70160. function TGATools() {
  70161. }
  70162. TGATools.GetTGAHeader = function (data) {
  70163. var offset = 0;
  70164. var header = {
  70165. id_length: data[offset++],
  70166. colormap_type: data[offset++],
  70167. image_type: data[offset++],
  70168. colormap_index: data[offset++] | data[offset++] << 8,
  70169. colormap_length: data[offset++] | data[offset++] << 8,
  70170. colormap_size: data[offset++],
  70171. origin: [
  70172. data[offset++] | data[offset++] << 8,
  70173. data[offset++] | data[offset++] << 8
  70174. ],
  70175. width: data[offset++] | data[offset++] << 8,
  70176. height: data[offset++] | data[offset++] << 8,
  70177. pixel_size: data[offset++],
  70178. flags: data[offset++]
  70179. };
  70180. return header;
  70181. };
  70182. TGATools.UploadContent = function (gl, data) {
  70183. // Not enough data to contain header ?
  70184. if (data.length < 19) {
  70185. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70186. return;
  70187. }
  70188. // Read Header
  70189. var offset = 18;
  70190. var header = TGATools.GetTGAHeader(data);
  70191. // Assume it's a valid Targa file.
  70192. if (header.id_length + offset > data.length) {
  70193. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70194. return;
  70195. }
  70196. // Skip not needed data
  70197. offset += header.id_length;
  70198. var use_rle = false;
  70199. var use_pal = false;
  70200. var use_grey = false;
  70201. // Get some informations.
  70202. switch (header.image_type) {
  70203. case TGATools._TYPE_RLE_INDEXED:
  70204. use_rle = true;
  70205. case TGATools._TYPE_INDEXED:
  70206. use_pal = true;
  70207. break;
  70208. case TGATools._TYPE_RLE_RGB:
  70209. use_rle = true;
  70210. case TGATools._TYPE_RGB:
  70211. // use_rgb = true;
  70212. break;
  70213. case TGATools._TYPE_RLE_GREY:
  70214. use_rle = true;
  70215. case TGATools._TYPE_GREY:
  70216. use_grey = true;
  70217. break;
  70218. }
  70219. var pixel_data;
  70220. // var numAlphaBits = header.flags & 0xf;
  70221. var pixel_size = header.pixel_size >> 3;
  70222. var pixel_total = header.width * header.height * pixel_size;
  70223. // Read palettes
  70224. var palettes;
  70225. if (use_pal) {
  70226. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70227. }
  70228. // Read LRE
  70229. if (use_rle) {
  70230. pixel_data = new Uint8Array(pixel_total);
  70231. var c, count, i;
  70232. var localOffset = 0;
  70233. var pixels = new Uint8Array(pixel_size);
  70234. while (offset < pixel_total && localOffset < pixel_total) {
  70235. c = data[offset++];
  70236. count = (c & 0x7f) + 1;
  70237. // RLE pixels
  70238. if (c & 0x80) {
  70239. // Bind pixel tmp array
  70240. for (i = 0; i < pixel_size; ++i) {
  70241. pixels[i] = data[offset++];
  70242. }
  70243. // Copy pixel array
  70244. for (i = 0; i < count; ++i) {
  70245. pixel_data.set(pixels, localOffset + i * pixel_size);
  70246. }
  70247. localOffset += pixel_size * count;
  70248. }
  70249. else {
  70250. count *= pixel_size;
  70251. for (i = 0; i < count; ++i) {
  70252. pixel_data[localOffset + i] = data[offset++];
  70253. }
  70254. localOffset += count;
  70255. }
  70256. }
  70257. }
  70258. else {
  70259. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70260. }
  70261. // Load to texture
  70262. var x_start, y_start, x_step, y_step, y_end, x_end;
  70263. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70264. default:
  70265. case TGATools._ORIGIN_UL:
  70266. x_start = 0;
  70267. x_step = 1;
  70268. x_end = header.width;
  70269. y_start = 0;
  70270. y_step = 1;
  70271. y_end = header.height;
  70272. break;
  70273. case TGATools._ORIGIN_BL:
  70274. x_start = 0;
  70275. x_step = 1;
  70276. x_end = header.width;
  70277. y_start = header.height - 1;
  70278. y_step = -1;
  70279. y_end = -1;
  70280. break;
  70281. case TGATools._ORIGIN_UR:
  70282. x_start = header.width - 1;
  70283. x_step = -1;
  70284. x_end = -1;
  70285. y_start = 0;
  70286. y_step = 1;
  70287. y_end = header.height;
  70288. break;
  70289. case TGATools._ORIGIN_BR:
  70290. x_start = header.width - 1;
  70291. x_step = -1;
  70292. x_end = -1;
  70293. y_start = header.height - 1;
  70294. y_step = -1;
  70295. y_end = -1;
  70296. break;
  70297. }
  70298. // Load the specify method
  70299. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70300. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70301. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70302. };
  70303. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70304. var image = pixel_data, colormap = palettes;
  70305. var width = header.width, height = header.height;
  70306. var color, i = 0, x, y;
  70307. var imageData = new Uint8Array(width * height * 4);
  70308. for (y = y_start; y !== y_end; y += y_step) {
  70309. for (x = x_start; x !== x_end; x += x_step, i++) {
  70310. color = image[i];
  70311. imageData[(x + width * y) * 4 + 3] = 255;
  70312. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70313. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70314. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70315. }
  70316. }
  70317. return imageData;
  70318. };
  70319. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70320. var image = pixel_data;
  70321. var width = header.width, height = header.height;
  70322. var color, i = 0, x, y;
  70323. var imageData = new Uint8Array(width * height * 4);
  70324. for (y = y_start; y !== y_end; y += y_step) {
  70325. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70326. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70327. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70328. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70329. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70330. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70331. }
  70332. }
  70333. return imageData;
  70334. };
  70335. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70336. var image = pixel_data;
  70337. var width = header.width, height = header.height;
  70338. var i = 0, x, y;
  70339. var imageData = new Uint8Array(width * height * 4);
  70340. for (y = y_start; y !== y_end; y += y_step) {
  70341. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70342. imageData[(x + width * y) * 4 + 3] = 255;
  70343. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70344. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70345. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70346. }
  70347. }
  70348. return imageData;
  70349. };
  70350. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70351. var image = pixel_data;
  70352. var width = header.width, height = header.height;
  70353. var i = 0, x, y;
  70354. var imageData = new Uint8Array(width * height * 4);
  70355. for (y = y_start; y !== y_end; y += y_step) {
  70356. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70357. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70358. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70359. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70360. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70361. }
  70362. }
  70363. return imageData;
  70364. };
  70365. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70366. var image = pixel_data;
  70367. var width = header.width, height = header.height;
  70368. var color, i = 0, x, y;
  70369. var imageData = new Uint8Array(width * height * 4);
  70370. for (y = y_start; y !== y_end; y += y_step) {
  70371. for (x = x_start; x !== x_end; x += x_step, i++) {
  70372. color = image[i];
  70373. imageData[(x + width * y) * 4 + 0] = color;
  70374. imageData[(x + width * y) * 4 + 1] = color;
  70375. imageData[(x + width * y) * 4 + 2] = color;
  70376. imageData[(x + width * y) * 4 + 3] = 255;
  70377. }
  70378. }
  70379. return imageData;
  70380. };
  70381. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70382. var image = pixel_data;
  70383. var width = header.width, height = header.height;
  70384. var i = 0, x, y;
  70385. var imageData = new Uint8Array(width * height * 4);
  70386. for (y = y_start; y !== y_end; y += y_step) {
  70387. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70388. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70389. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70391. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70392. }
  70393. }
  70394. return imageData;
  70395. };
  70396. //private static _TYPE_NO_DATA = 0;
  70397. TGATools._TYPE_INDEXED = 1;
  70398. TGATools._TYPE_RGB = 2;
  70399. TGATools._TYPE_GREY = 3;
  70400. TGATools._TYPE_RLE_INDEXED = 9;
  70401. TGATools._TYPE_RLE_RGB = 10;
  70402. TGATools._TYPE_RLE_GREY = 11;
  70403. TGATools._ORIGIN_MASK = 0x30;
  70404. TGATools._ORIGIN_SHIFT = 0x04;
  70405. TGATools._ORIGIN_BL = 0x00;
  70406. TGATools._ORIGIN_BR = 0x01;
  70407. TGATools._ORIGIN_UL = 0x02;
  70408. TGATools._ORIGIN_UR = 0x03;
  70409. return TGATools;
  70410. }());
  70411. BABYLON.TGATools = TGATools;
  70412. })(BABYLON || (BABYLON = {}));
  70413. //# sourceMappingURL=babylon.tga.js.map
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70417. // All values and structures referenced from:
  70418. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70419. var DDS_MAGIC = 0x20534444;
  70420. var
  70421. //DDSD_CAPS = 0x1,
  70422. //DDSD_HEIGHT = 0x2,
  70423. //DDSD_WIDTH = 0x4,
  70424. //DDSD_PITCH = 0x8,
  70425. //DDSD_PIXELFORMAT = 0x1000,
  70426. DDSD_MIPMAPCOUNT = 0x20000;
  70427. //DDSD_LINEARSIZE = 0x80000,
  70428. //DDSD_DEPTH = 0x800000;
  70429. // var DDSCAPS_COMPLEX = 0x8,
  70430. // DDSCAPS_MIPMAP = 0x400000,
  70431. // DDSCAPS_TEXTURE = 0x1000;
  70432. var DDSCAPS2_CUBEMAP = 0x200;
  70433. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70434. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70435. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70436. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70437. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70438. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70439. // DDSCAPS2_VOLUME = 0x200000;
  70440. var
  70441. //DDPF_ALPHAPIXELS = 0x1,
  70442. //DDPF_ALPHA = 0x2,
  70443. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70444. //DDPF_YUV = 0x200,
  70445. DDPF_LUMINANCE = 0x20000;
  70446. function FourCCToInt32(value) {
  70447. return value.charCodeAt(0) +
  70448. (value.charCodeAt(1) << 8) +
  70449. (value.charCodeAt(2) << 16) +
  70450. (value.charCodeAt(3) << 24);
  70451. }
  70452. function Int32ToFourCC(value) {
  70453. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70454. }
  70455. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70456. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70457. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70458. var FOURCC_DX10 = FourCCToInt32("DX10");
  70459. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70460. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70461. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70462. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70463. var headerLengthInt = 31; // The header length in 32 bit ints
  70464. // Offsets into the header array
  70465. var off_magic = 0;
  70466. var off_size = 1;
  70467. var off_flags = 2;
  70468. var off_height = 3;
  70469. var off_width = 4;
  70470. var off_mipmapCount = 7;
  70471. var off_pfFlags = 20;
  70472. var off_pfFourCC = 21;
  70473. var off_RGBbpp = 22;
  70474. // var off_RMask = 23;
  70475. // var off_GMask = 24;
  70476. // var off_BMask = 25;
  70477. // var off_AMask = 26;
  70478. // var off_caps1 = 27;
  70479. var off_caps2 = 28;
  70480. // var off_caps3 = 29;
  70481. // var off_caps4 = 30;
  70482. var off_dxgiFormat = 32;
  70483. ;
  70484. var DDSTools = /** @class */ (function () {
  70485. function DDSTools() {
  70486. }
  70487. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70488. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70489. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70490. var mipmapCount = 1;
  70491. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70492. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70493. }
  70494. var fourCC = header[off_pfFourCC];
  70495. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70496. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70497. switch (fourCC) {
  70498. case FOURCC_D3DFMT_R16G16B16A16F:
  70499. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70500. break;
  70501. case FOURCC_D3DFMT_R32G32B32A32F:
  70502. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70503. break;
  70504. case FOURCC_DX10:
  70505. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70506. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70507. break;
  70508. }
  70509. }
  70510. return {
  70511. width: header[off_width],
  70512. height: header[off_height],
  70513. mipmapCount: mipmapCount,
  70514. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70515. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70516. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70517. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70518. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70519. dxgiFormat: dxgiFormat,
  70520. textureType: textureType
  70521. };
  70522. };
  70523. DDSTools._ToHalfFloat = function (value) {
  70524. if (!DDSTools._FloatView) {
  70525. DDSTools._FloatView = new Float32Array(1);
  70526. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70527. }
  70528. DDSTools._FloatView[0] = value;
  70529. var x = DDSTools._Int32View[0];
  70530. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70531. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70532. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70533. /* If zero, or denormal, or exponent underflows too much for a denormal
  70534. * half, return signed zero. */
  70535. if (e < 103) {
  70536. return bits;
  70537. }
  70538. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70539. if (e > 142) {
  70540. bits |= 0x7c00;
  70541. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70542. * not Inf, so make sure we set one mantissa bit too. */
  70543. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70544. return bits;
  70545. }
  70546. /* If exponent underflows but not too much, return a denormal */
  70547. if (e < 113) {
  70548. m |= 0x0800;
  70549. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70550. * to 1, which is OK. */
  70551. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70552. return bits;
  70553. }
  70554. bits |= ((e - 112) << 10) | (m >> 1);
  70555. bits += m & 1;
  70556. return bits;
  70557. };
  70558. DDSTools._FromHalfFloat = function (value) {
  70559. var s = (value & 0x8000) >> 15;
  70560. var e = (value & 0x7C00) >> 10;
  70561. var f = value & 0x03FF;
  70562. if (e === 0) {
  70563. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70564. }
  70565. else if (e == 0x1F) {
  70566. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70567. }
  70568. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70569. };
  70570. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70571. var destArray = new Float32Array(dataLength);
  70572. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70573. var index = 0;
  70574. for (var y = 0; y < height; y++) {
  70575. for (var x = 0; x < width; x++) {
  70576. var srcPos = (x + y * width) * 4;
  70577. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70578. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70579. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70580. if (DDSTools.StoreLODInAlphaChannel) {
  70581. destArray[index + 3] = lod;
  70582. }
  70583. else {
  70584. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70585. }
  70586. index += 4;
  70587. }
  70588. }
  70589. return destArray;
  70590. };
  70591. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70592. if (DDSTools.StoreLODInAlphaChannel) {
  70593. var destArray = new Uint16Array(dataLength);
  70594. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70595. var index = 0;
  70596. for (var y = 0; y < height; y++) {
  70597. for (var x = 0; x < width; x++) {
  70598. var srcPos = (x + y * width) * 4;
  70599. destArray[index] = srcData[srcPos];
  70600. destArray[index + 1] = srcData[srcPos + 1];
  70601. destArray[index + 2] = srcData[srcPos + 2];
  70602. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70603. index += 4;
  70604. }
  70605. }
  70606. return destArray;
  70607. }
  70608. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70609. };
  70610. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70611. if (DDSTools.StoreLODInAlphaChannel) {
  70612. var destArray = new Float32Array(dataLength);
  70613. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70614. var index = 0;
  70615. for (var y = 0; y < height; y++) {
  70616. for (var x = 0; x < width; x++) {
  70617. var srcPos = (x + y * width) * 4;
  70618. destArray[index] = srcData[srcPos];
  70619. destArray[index + 1] = srcData[srcPos + 1];
  70620. destArray[index + 2] = srcData[srcPos + 2];
  70621. destArray[index + 3] = lod;
  70622. index += 4;
  70623. }
  70624. }
  70625. return destArray;
  70626. }
  70627. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70628. };
  70629. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70630. var destArray = new Uint8Array(dataLength);
  70631. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70632. var index = 0;
  70633. for (var y = 0; y < height; y++) {
  70634. for (var x = 0; x < width; x++) {
  70635. var srcPos = (x + y * width) * 4;
  70636. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70637. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70638. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70639. if (DDSTools.StoreLODInAlphaChannel) {
  70640. destArray[index + 3] = lod;
  70641. }
  70642. else {
  70643. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70644. }
  70645. index += 4;
  70646. }
  70647. }
  70648. return destArray;
  70649. };
  70650. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70651. var destArray = new Uint8Array(dataLength);
  70652. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70653. var index = 0;
  70654. for (var y = 0; y < height; y++) {
  70655. for (var x = 0; x < width; x++) {
  70656. var srcPos = (x + y * width) * 4;
  70657. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70658. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70659. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70660. if (DDSTools.StoreLODInAlphaChannel) {
  70661. destArray[index + 3] = lod;
  70662. }
  70663. else {
  70664. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70665. }
  70666. index += 4;
  70667. }
  70668. }
  70669. return destArray;
  70670. };
  70671. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70672. var byteArray = new Uint8Array(dataLength);
  70673. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70674. var index = 0;
  70675. for (var y = 0; y < height; y++) {
  70676. for (var x = 0; x < width; x++) {
  70677. var srcPos = (x + y * width) * 4;
  70678. byteArray[index] = srcData[srcPos + 2];
  70679. byteArray[index + 1] = srcData[srcPos + 1];
  70680. byteArray[index + 2] = srcData[srcPos];
  70681. byteArray[index + 3] = srcData[srcPos + 3];
  70682. index += 4;
  70683. }
  70684. }
  70685. return byteArray;
  70686. };
  70687. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70688. var byteArray = new Uint8Array(dataLength);
  70689. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70690. var index = 0;
  70691. for (var y = 0; y < height; y++) {
  70692. for (var x = 0; x < width; x++) {
  70693. var srcPos = (x + y * width) * 3;
  70694. byteArray[index] = srcData[srcPos + 2];
  70695. byteArray[index + 1] = srcData[srcPos + 1];
  70696. byteArray[index + 2] = srcData[srcPos];
  70697. index += 3;
  70698. }
  70699. }
  70700. return byteArray;
  70701. };
  70702. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70703. var byteArray = new Uint8Array(dataLength);
  70704. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70705. var index = 0;
  70706. for (var y = 0; y < height; y++) {
  70707. for (var x = 0; x < width; x++) {
  70708. var srcPos = (x + y * width);
  70709. byteArray[index] = srcData[srcPos];
  70710. index++;
  70711. }
  70712. }
  70713. return byteArray;
  70714. };
  70715. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70716. if (lodIndex === void 0) { lodIndex = -1; }
  70717. var ext = engine.getCaps().s3tc;
  70718. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70719. var fourCC, width, height, dataLength = 0, dataOffset;
  70720. var byteArray, mipmapCount, mip;
  70721. var internalFormat = 0;
  70722. var format = 0;
  70723. var blockBytes = 1;
  70724. if (header[off_magic] !== DDS_MAGIC) {
  70725. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70726. return;
  70727. }
  70728. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70729. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70730. return;
  70731. }
  70732. if (info.isCompressed && !ext) {
  70733. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70734. return;
  70735. }
  70736. var bpp = header[off_RGBbpp];
  70737. dataOffset = header[off_size] + 4;
  70738. var computeFormats = false;
  70739. if (info.isFourCC) {
  70740. fourCC = header[off_pfFourCC];
  70741. switch (fourCC) {
  70742. case FOURCC_DXT1:
  70743. blockBytes = 8;
  70744. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70745. break;
  70746. case FOURCC_DXT3:
  70747. blockBytes = 16;
  70748. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70749. break;
  70750. case FOURCC_DXT5:
  70751. blockBytes = 16;
  70752. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70753. break;
  70754. case FOURCC_D3DFMT_R16G16B16A16F:
  70755. computeFormats = true;
  70756. break;
  70757. case FOURCC_D3DFMT_R32G32B32A32F:
  70758. computeFormats = true;
  70759. break;
  70760. case FOURCC_DX10:
  70761. // There is an additionnal header so dataOffset need to be changed
  70762. dataOffset += 5 * 4; // 5 uints
  70763. var supported = false;
  70764. switch (info.dxgiFormat) {
  70765. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70766. computeFormats = true;
  70767. supported = true;
  70768. break;
  70769. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70770. info.isRGB = true;
  70771. info.isFourCC = false;
  70772. bpp = 32;
  70773. supported = true;
  70774. break;
  70775. }
  70776. if (supported) {
  70777. break;
  70778. }
  70779. default:
  70780. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70781. return;
  70782. }
  70783. }
  70784. if (computeFormats) {
  70785. format = engine._getWebGLTextureType(info.textureType);
  70786. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70787. }
  70788. mipmapCount = 1;
  70789. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70790. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70791. }
  70792. for (var face = 0; face < faces; face++) {
  70793. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70794. width = header[off_width];
  70795. height = header[off_height];
  70796. for (mip = 0; mip < mipmapCount; ++mip) {
  70797. if (lodIndex === -1 || lodIndex === mip) {
  70798. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70799. var i = (lodIndex === -1) ? mip : 0;
  70800. if (!info.isCompressed && info.isFourCC) {
  70801. dataLength = width * height * 4;
  70802. var floatArray = null;
  70803. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70804. if (bpp === 128) {
  70805. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70806. }
  70807. else if (bpp === 64) {
  70808. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70809. }
  70810. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70811. format = engine._getWebGLTextureType(info.textureType);
  70812. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70813. }
  70814. else {
  70815. if (bpp === 128) {
  70816. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70817. }
  70818. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70819. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70820. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70821. format = engine._getWebGLTextureType(info.textureType);
  70822. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70823. }
  70824. else {
  70825. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70826. }
  70827. }
  70828. if (floatArray) {
  70829. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70830. }
  70831. }
  70832. else if (info.isRGB) {
  70833. if (bpp === 24) {
  70834. dataLength = width * height * 3;
  70835. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70836. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70837. }
  70838. else {
  70839. dataLength = width * height * 4;
  70840. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70841. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70842. }
  70843. }
  70844. else if (info.isLuminance) {
  70845. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70846. var unpaddedRowSize = width;
  70847. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70848. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70849. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70850. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70851. }
  70852. else {
  70853. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70854. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70855. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70856. }
  70857. }
  70858. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70859. width *= 0.5;
  70860. height *= 0.5;
  70861. width = Math.max(1.0, width);
  70862. height = Math.max(1.0, height);
  70863. }
  70864. if (currentFace !== undefined) {
  70865. // Loading a single face
  70866. break;
  70867. }
  70868. }
  70869. };
  70870. DDSTools.StoreLODInAlphaChannel = false;
  70871. return DDSTools;
  70872. }());
  70873. BABYLON.DDSTools = DDSTools;
  70874. })(BABYLON || (BABYLON = {}));
  70875. //# sourceMappingURL=babylon.dds.js.map
  70876. var BABYLON;
  70877. (function (BABYLON) {
  70878. /**
  70879. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70880. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70881. */
  70882. var KhronosTextureContainer = /** @class */ (function () {
  70883. /**
  70884. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70885. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70886. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70887. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70888. */
  70889. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70890. this.arrayBuffer = arrayBuffer;
  70891. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70892. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70893. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70894. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70895. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70896. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70897. BABYLON.Tools.Error("texture missing KTX identifier");
  70898. return;
  70899. }
  70900. // load the reset of the header in native 32 bit int
  70901. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70902. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70903. var oppositeEndianess = header[0] === 0x01020304;
  70904. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70905. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70906. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70907. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70908. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70909. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70910. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70911. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70912. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70913. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70914. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70915. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70916. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70917. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70918. if (this.glType !== 0) {
  70919. BABYLON.Tools.Error("only compressed formats currently supported");
  70920. return;
  70921. }
  70922. else {
  70923. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70924. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70925. }
  70926. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70927. BABYLON.Tools.Error("only 2D textures currently supported");
  70928. return;
  70929. }
  70930. if (this.numberOfArrayElements !== 0) {
  70931. BABYLON.Tools.Error("texture arrays not currently supported");
  70932. return;
  70933. }
  70934. if (this.numberOfFaces !== facesExpected) {
  70935. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70936. return;
  70937. }
  70938. // we now have a completely validated file, so could use existence of loadType as success
  70939. // would need to make this more elaborate & adjust checks above to support more than one load type
  70940. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70941. }
  70942. // not as fast hardware based, but will probably never need to use
  70943. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70944. return ((val & 0xFF) << 24)
  70945. | ((val & 0xFF00) << 8)
  70946. | ((val >> 8) & 0xFF00)
  70947. | ((val >> 24) & 0xFF);
  70948. };
  70949. /**
  70950. * It is assumed that the texture has already been created & is currently bound
  70951. */
  70952. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70953. switch (this.loadType) {
  70954. case KhronosTextureContainer.COMPRESSED_2D:
  70955. this._upload2DCompressedLevels(gl, loadMipmaps);
  70956. break;
  70957. case KhronosTextureContainer.TEX_2D:
  70958. case KhronosTextureContainer.COMPRESSED_3D:
  70959. case KhronosTextureContainer.TEX_3D:
  70960. }
  70961. };
  70962. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70963. // initialize width & height for level 1
  70964. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70965. var width = this.pixelWidth;
  70966. var height = this.pixelHeight;
  70967. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70968. for (var level = 0; level < mipmapCount; level++) {
  70969. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70970. for (var face = 0; face < this.numberOfFaces; face++) {
  70971. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70972. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70973. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70974. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70975. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70976. }
  70977. width = Math.max(1.0, width * 0.5);
  70978. height = Math.max(1.0, height * 0.5);
  70979. }
  70980. };
  70981. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70982. // load types
  70983. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70984. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70985. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70986. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70987. return KhronosTextureContainer;
  70988. }());
  70989. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  70990. })(BABYLON || (BABYLON = {}));
  70991. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70992. var BABYLON;
  70993. (function (BABYLON) {
  70994. var Debug = /** @class */ (function () {
  70995. function Debug() {
  70996. }
  70997. Debug.AxesViewer = /** @class */ (function () {
  70998. function AxesViewer(scene, scaleLines) {
  70999. if (scaleLines === void 0) { scaleLines = 1; }
  71000. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71001. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71002. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71003. this.scaleLines = 1;
  71004. this.scaleLines = scaleLines;
  71005. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  71006. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  71007. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  71008. this._xmesh.renderingGroupId = 2;
  71009. this._ymesh.renderingGroupId = 2;
  71010. this._zmesh.renderingGroupId = 2;
  71011. this._xmesh.material.checkReadyOnlyOnce = true;
  71012. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  71013. this._ymesh.material.checkReadyOnlyOnce = true;
  71014. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71015. this._zmesh.material.checkReadyOnlyOnce = true;
  71016. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71017. this.scene = scene;
  71018. }
  71019. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71020. var scaleLines = this.scaleLines;
  71021. if (this._xmesh) {
  71022. this._xmesh.position.copyFrom(position);
  71023. }
  71024. if (this._ymesh) {
  71025. this._ymesh.position.copyFrom(position);
  71026. }
  71027. if (this._zmesh) {
  71028. this._zmesh.position.copyFrom(position);
  71029. }
  71030. var point2 = this._xline[1];
  71031. point2.x = xaxis.x * scaleLines;
  71032. point2.y = xaxis.y * scaleLines;
  71033. point2.z = xaxis.z * scaleLines;
  71034. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71035. point2 = this._yline[1];
  71036. point2.x = yaxis.x * scaleLines;
  71037. point2.y = yaxis.y * scaleLines;
  71038. point2.z = yaxis.z * scaleLines;
  71039. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71040. point2 = this._zline[1];
  71041. point2.x = zaxis.x * scaleLines;
  71042. point2.y = zaxis.y * scaleLines;
  71043. point2.z = zaxis.z * scaleLines;
  71044. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71045. };
  71046. AxesViewer.prototype.dispose = function () {
  71047. if (this._xmesh) {
  71048. this._xmesh.dispose();
  71049. }
  71050. if (this._ymesh) {
  71051. this._ymesh.dispose();
  71052. }
  71053. if (this._zmesh) {
  71054. this._zmesh.dispose();
  71055. }
  71056. this._xmesh = null;
  71057. this._ymesh = null;
  71058. this._zmesh = null;
  71059. this.scene = null;
  71060. };
  71061. return AxesViewer;
  71062. }());
  71063. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71064. __extends(BoneAxesViewer, _super);
  71065. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71066. if (scaleLines === void 0) { scaleLines = 1; }
  71067. var _this = _super.call(this, scene, scaleLines) || this;
  71068. _this.pos = BABYLON.Vector3.Zero();
  71069. _this.xaxis = BABYLON.Vector3.Zero();
  71070. _this.yaxis = BABYLON.Vector3.Zero();
  71071. _this.zaxis = BABYLON.Vector3.Zero();
  71072. _this.mesh = mesh;
  71073. _this.bone = bone;
  71074. return _this;
  71075. }
  71076. BoneAxesViewer.prototype.update = function () {
  71077. if (!this.mesh || !this.bone) {
  71078. return;
  71079. }
  71080. var bone = this.bone;
  71081. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71082. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71083. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71084. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71085. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71086. };
  71087. BoneAxesViewer.prototype.dispose = function () {
  71088. if (this.mesh) {
  71089. this.mesh = null;
  71090. this.bone = null;
  71091. _super.prototype.dispose.call(this);
  71092. }
  71093. };
  71094. return BoneAxesViewer;
  71095. }(Debug.AxesViewer));
  71096. Debug.PhysicsViewer = /** @class */ (function () {
  71097. function PhysicsViewer(scene) {
  71098. this._impostors = [];
  71099. this._meshes = [];
  71100. this._numMeshes = 0;
  71101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71102. var physicEngine = this._scene.getPhysicsEngine();
  71103. if (physicEngine) {
  71104. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71105. }
  71106. }
  71107. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71108. var plugin = this._physicsEnginePlugin;
  71109. for (var i = 0; i < this._numMeshes; i++) {
  71110. var impostor = this._impostors[i];
  71111. if (!impostor) {
  71112. continue;
  71113. }
  71114. if (impostor.isDisposed) {
  71115. this.hideImpostor(this._impostors[i--]);
  71116. }
  71117. else {
  71118. var mesh = this._meshes[i];
  71119. if (mesh && plugin) {
  71120. plugin.syncMeshWithImpostor(mesh, impostor);
  71121. }
  71122. }
  71123. }
  71124. };
  71125. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71126. if (!this._scene) {
  71127. return;
  71128. }
  71129. for (var i = 0; i < this._numMeshes; i++) {
  71130. if (this._impostors[i] == impostor) {
  71131. return;
  71132. }
  71133. }
  71134. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71135. if (debugMesh) {
  71136. this._impostors[this._numMeshes] = impostor;
  71137. this._meshes[this._numMeshes] = debugMesh;
  71138. if (this._numMeshes === 0) {
  71139. this._renderFunction = this._updateDebugMeshes.bind(this);
  71140. this._scene.registerBeforeRender(this._renderFunction);
  71141. }
  71142. this._numMeshes++;
  71143. }
  71144. };
  71145. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71146. if (!impostor || !this._scene) {
  71147. return;
  71148. }
  71149. var removed = false;
  71150. for (var i = 0; i < this._numMeshes; i++) {
  71151. if (this._impostors[i] == impostor) {
  71152. var mesh = this._meshes[i];
  71153. if (!mesh) {
  71154. continue;
  71155. }
  71156. this._scene.removeMesh(mesh);
  71157. mesh.dispose();
  71158. this._numMeshes--;
  71159. if (this._numMeshes > 0) {
  71160. this._meshes[i] = this._meshes[this._numMeshes];
  71161. this._impostors[i] = this._impostors[this._numMeshes];
  71162. this._meshes[this._numMeshes] = null;
  71163. this._impostors[this._numMeshes] = null;
  71164. }
  71165. else {
  71166. this._meshes[0] = null;
  71167. this._impostors[0] = null;
  71168. }
  71169. removed = true;
  71170. break;
  71171. }
  71172. }
  71173. if (removed && this._numMeshes === 0) {
  71174. this._scene.unregisterBeforeRender(this._renderFunction);
  71175. }
  71176. };
  71177. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71178. if (!this._debugMaterial) {
  71179. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71180. this._debugMaterial.wireframe = true;
  71181. }
  71182. return this._debugMaterial;
  71183. };
  71184. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71185. if (!this._debugBoxMesh) {
  71186. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71187. this._debugBoxMesh.renderingGroupId = 1;
  71188. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71189. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71190. scene.removeMesh(this._debugBoxMesh);
  71191. }
  71192. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71193. };
  71194. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71195. if (!this._debugSphereMesh) {
  71196. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71197. this._debugSphereMesh.renderingGroupId = 1;
  71198. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71199. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71200. scene.removeMesh(this._debugSphereMesh);
  71201. }
  71202. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71203. };
  71204. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71205. var mesh = null;
  71206. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71207. mesh = this._getDebugBoxMesh(scene);
  71208. impostor.getBoxSizeToRef(mesh.scaling);
  71209. }
  71210. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71211. mesh = this._getDebugSphereMesh(scene);
  71212. var radius = impostor.getRadius();
  71213. mesh.scaling.x = radius * 2;
  71214. mesh.scaling.y = radius * 2;
  71215. mesh.scaling.z = radius * 2;
  71216. }
  71217. return mesh;
  71218. };
  71219. PhysicsViewer.prototype.dispose = function () {
  71220. for (var i = 0; i < this._numMeshes; i++) {
  71221. this.hideImpostor(this._impostors[i]);
  71222. }
  71223. if (this._debugBoxMesh) {
  71224. this._debugBoxMesh.dispose();
  71225. }
  71226. if (this._debugSphereMesh) {
  71227. this._debugSphereMesh.dispose();
  71228. }
  71229. if (this._debugMaterial) {
  71230. this._debugMaterial.dispose();
  71231. }
  71232. this._impostors.length = 0;
  71233. this._scene = null;
  71234. this._physicsEnginePlugin = null;
  71235. };
  71236. return PhysicsViewer;
  71237. }());
  71238. Debug.SkeletonViewer = /** @class */ (function () {
  71239. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71240. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71241. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71242. this.skeleton = skeleton;
  71243. this.mesh = mesh;
  71244. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71245. this.renderingGroupId = renderingGroupId;
  71246. this.color = BABYLON.Color3.White();
  71247. this._debugLines = new Array();
  71248. this._isEnabled = false;
  71249. this._scene = scene;
  71250. this.update();
  71251. this._renderFunction = this.update.bind(this);
  71252. }
  71253. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71254. get: function () {
  71255. return this._isEnabled;
  71256. },
  71257. set: function (value) {
  71258. if (this._isEnabled === value) {
  71259. return;
  71260. }
  71261. this._isEnabled = value;
  71262. if (value) {
  71263. this._scene.registerBeforeRender(this._renderFunction);
  71264. }
  71265. else {
  71266. this._scene.unregisterBeforeRender(this._renderFunction);
  71267. }
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71273. if (x === void 0) { x = 0; }
  71274. if (y === void 0) { y = 0; }
  71275. if (z === void 0) { z = 0; }
  71276. var tmat = BABYLON.Tmp.Matrix[0];
  71277. var parentBone = bone.getParent();
  71278. tmat.copyFrom(bone.getLocalMatrix());
  71279. if (x !== 0 || y !== 0 || z !== 0) {
  71280. var tmat2 = BABYLON.Tmp.Matrix[1];
  71281. BABYLON.Matrix.IdentityToRef(tmat2);
  71282. tmat2.m[12] = x;
  71283. tmat2.m[13] = y;
  71284. tmat2.m[14] = z;
  71285. tmat2.multiplyToRef(tmat, tmat);
  71286. }
  71287. if (parentBone) {
  71288. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71289. }
  71290. tmat.multiplyToRef(meshMat, tmat);
  71291. position.x = tmat.m[12];
  71292. position.y = tmat.m[13];
  71293. position.z = tmat.m[14];
  71294. };
  71295. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71296. var len = bones.length;
  71297. var meshPos = this.mesh.position;
  71298. for (var i = 0; i < len; i++) {
  71299. var bone = bones[i];
  71300. var points = this._debugLines[i];
  71301. if (!points) {
  71302. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71303. this._debugLines[i] = points;
  71304. }
  71305. this._getBonePosition(points[0], bone, meshMat);
  71306. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71307. points[0].subtractInPlace(meshPos);
  71308. points[1].subtractInPlace(meshPos);
  71309. }
  71310. };
  71311. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71312. var len = bones.length;
  71313. var boneNum = 0;
  71314. var meshPos = this.mesh.position;
  71315. for (var i = len - 1; i >= 0; i--) {
  71316. var childBone = bones[i];
  71317. var parentBone = childBone.getParent();
  71318. if (!parentBone) {
  71319. continue;
  71320. }
  71321. var points = this._debugLines[boneNum];
  71322. if (!points) {
  71323. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71324. this._debugLines[boneNum] = points;
  71325. }
  71326. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71327. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71328. points[0].subtractInPlace(meshPos);
  71329. points[1].subtractInPlace(meshPos);
  71330. boneNum++;
  71331. }
  71332. };
  71333. SkeletonViewer.prototype.update = function () {
  71334. if (this.autoUpdateBonesMatrices) {
  71335. this.skeleton.computeAbsoluteTransforms();
  71336. }
  71337. if (this.skeleton.bones[0].length === undefined) {
  71338. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71339. }
  71340. else {
  71341. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71342. }
  71343. if (!this._debugMesh) {
  71344. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71345. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71346. }
  71347. else {
  71348. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71349. }
  71350. this._debugMesh.position.copyFrom(this.mesh.position);
  71351. this._debugMesh.color = this.color;
  71352. };
  71353. SkeletonViewer.prototype.dispose = function () {
  71354. if (this._debugMesh) {
  71355. this.isEnabled = false;
  71356. this._debugMesh.dispose();
  71357. this._debugMesh = null;
  71358. }
  71359. };
  71360. return SkeletonViewer;
  71361. }());
  71362. return Debug;
  71363. }());
  71364. BABYLON.Debug = Debug;
  71365. })(BABYLON || (BABYLON = {}));
  71366. //# sourceMappingURL=babylon.debugModules.js.map
  71367. var BABYLON;
  71368. (function (BABYLON) {
  71369. var RayHelper = /** @class */ (function () {
  71370. function RayHelper(ray) {
  71371. this.ray = ray;
  71372. }
  71373. RayHelper.CreateAndShow = function (ray, scene, color) {
  71374. var helper = new RayHelper(ray);
  71375. helper.show(scene, color);
  71376. return helper;
  71377. };
  71378. RayHelper.prototype.show = function (scene, color) {
  71379. if (!this._renderFunction && this.ray) {
  71380. var ray = this.ray;
  71381. this._renderFunction = this._render.bind(this);
  71382. this._scene = scene;
  71383. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71384. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71385. if (this._renderFunction) {
  71386. this._scene.registerBeforeRender(this._renderFunction);
  71387. }
  71388. }
  71389. if (color && this._renderLine) {
  71390. this._renderLine.color.copyFrom(color);
  71391. }
  71392. };
  71393. RayHelper.prototype.hide = function () {
  71394. if (this._renderFunction && this._scene) {
  71395. this._scene.unregisterBeforeRender(this._renderFunction);
  71396. this._scene = null;
  71397. this._renderFunction = null;
  71398. if (this._renderLine) {
  71399. this._renderLine.dispose();
  71400. this._renderLine = null;
  71401. }
  71402. this._renderPoints = [];
  71403. }
  71404. };
  71405. RayHelper.prototype._render = function () {
  71406. var ray = this.ray;
  71407. if (!ray) {
  71408. return;
  71409. }
  71410. var point = this._renderPoints[1];
  71411. var len = Math.min(ray.length, 1000000);
  71412. point.copyFrom(ray.direction);
  71413. point.scaleInPlace(len);
  71414. point.addInPlace(ray.origin);
  71415. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71416. };
  71417. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71418. this._attachedToMesh = mesh;
  71419. var ray = this.ray;
  71420. if (!ray) {
  71421. return;
  71422. }
  71423. if (!ray.direction) {
  71424. ray.direction = BABYLON.Vector3.Zero();
  71425. }
  71426. if (!ray.origin) {
  71427. ray.origin = BABYLON.Vector3.Zero();
  71428. }
  71429. if (length) {
  71430. ray.length = length;
  71431. }
  71432. if (!meshSpaceOrigin) {
  71433. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71434. }
  71435. if (!meshSpaceDirection) {
  71436. // -1 so that this will work with Mesh.lookAt
  71437. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71438. }
  71439. if (!this._meshSpaceDirection) {
  71440. this._meshSpaceDirection = meshSpaceDirection.clone();
  71441. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71442. }
  71443. else {
  71444. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71445. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71446. }
  71447. if (!this._updateToMeshFunction) {
  71448. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71449. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71450. }
  71451. this._updateToMesh();
  71452. };
  71453. RayHelper.prototype.detachFromMesh = function () {
  71454. if (this._attachedToMesh) {
  71455. if (this._updateToMeshFunction) {
  71456. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71457. }
  71458. this._attachedToMesh = null;
  71459. this._updateToMeshFunction = null;
  71460. }
  71461. };
  71462. RayHelper.prototype._updateToMesh = function () {
  71463. var ray = this.ray;
  71464. if (!this._attachedToMesh || !ray) {
  71465. return;
  71466. }
  71467. if (this._attachedToMesh._isDisposed) {
  71468. this.detachFromMesh();
  71469. return;
  71470. }
  71471. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71472. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71473. };
  71474. RayHelper.prototype.dispose = function () {
  71475. this.hide();
  71476. this.detachFromMesh();
  71477. this.ray = null;
  71478. };
  71479. return RayHelper;
  71480. }());
  71481. BABYLON.RayHelper = RayHelper;
  71482. })(BABYLON || (BABYLON = {}));
  71483. //# sourceMappingURL=babylon.rayHelper.js.map
  71484. var BABYLON;
  71485. (function (BABYLON) {
  71486. // load the inspector using require, if not present in the global namespace.
  71487. var DebugLayer = /** @class */ (function () {
  71488. function DebugLayer(scene) {
  71489. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71490. this._scene = scene;
  71491. // load inspector using require, if it doesn't exist on the global namespace.
  71492. }
  71493. /** Creates the inspector window. */
  71494. DebugLayer.prototype._createInspector = function (config) {
  71495. if (config === void 0) { config = {}; }
  71496. var popup = config.popup || false;
  71497. var initialTab = config.initialTab || 0;
  71498. var parentElement = config.parentElement || null;
  71499. if (!this._inspector) {
  71500. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71501. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71502. } // else nothing to do,; instance is already existing
  71503. };
  71504. DebugLayer.prototype.isVisible = function () {
  71505. if (!this._inspector) {
  71506. return false;
  71507. }
  71508. return true;
  71509. };
  71510. DebugLayer.prototype.hide = function () {
  71511. if (this._inspector) {
  71512. try {
  71513. this._inspector.dispose();
  71514. }
  71515. catch (e) {
  71516. // If the inspector has been removed directly from the inspector tool
  71517. }
  71518. this._inspector = null;
  71519. }
  71520. };
  71521. DebugLayer.prototype.show = function (config) {
  71522. if (config === void 0) { config = {}; }
  71523. if (typeof this.BJSINSPECTOR == 'undefined') {
  71524. // Load inspector and add it to the DOM
  71525. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71526. }
  71527. else {
  71528. // Otherwise creates the inspector
  71529. this._createInspector(config);
  71530. }
  71531. };
  71532. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71533. return DebugLayer;
  71534. }());
  71535. BABYLON.DebugLayer = DebugLayer;
  71536. })(BABYLON || (BABYLON = {}));
  71537. //# sourceMappingURL=babylon.debugLayer.js.map
  71538. var BABYLON;
  71539. (function (BABYLON) {
  71540. var BoundingBoxRenderer = /** @class */ (function () {
  71541. function BoundingBoxRenderer(scene) {
  71542. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71543. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71544. this.showBackLines = true;
  71545. this.renderList = new BABYLON.SmartArray(32);
  71546. this._vertexBuffers = {};
  71547. this._scene = scene;
  71548. }
  71549. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71550. if (this._colorShader) {
  71551. return;
  71552. }
  71553. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71554. attributes: [BABYLON.VertexBuffer.PositionKind],
  71555. uniforms: ["world", "viewProjection", "color"]
  71556. });
  71557. var engine = this._scene.getEngine();
  71558. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71559. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71560. this._createIndexBuffer();
  71561. };
  71562. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71563. var engine = this._scene.getEngine();
  71564. 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]);
  71565. };
  71566. BoundingBoxRenderer.prototype._rebuild = function () {
  71567. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71568. if (vb) {
  71569. vb._rebuild();
  71570. }
  71571. this._createIndexBuffer();
  71572. };
  71573. BoundingBoxRenderer.prototype.reset = function () {
  71574. this.renderList.reset();
  71575. };
  71576. BoundingBoxRenderer.prototype.render = function () {
  71577. if (this.renderList.length === 0) {
  71578. return;
  71579. }
  71580. this._prepareRessources();
  71581. if (!this._colorShader.isReady()) {
  71582. return;
  71583. }
  71584. var engine = this._scene.getEngine();
  71585. engine.setDepthWrite(false);
  71586. this._colorShader._preBind();
  71587. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71588. var boundingBox = this.renderList.data[boundingBoxIndex];
  71589. var min = boundingBox.minimum;
  71590. var max = boundingBox.maximum;
  71591. var diff = max.subtract(min);
  71592. var median = min.add(diff.scale(0.5));
  71593. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71594. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71595. .multiply(boundingBox.getWorldMatrix());
  71596. // VBOs
  71597. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71598. if (this.showBackLines) {
  71599. // Back
  71600. engine.setDepthFunctionToGreaterOrEqual();
  71601. this._scene.resetCachedMaterial();
  71602. this._colorShader.setColor4("color", this.backColor.toColor4());
  71603. this._colorShader.bind(worldMatrix);
  71604. // Draw order
  71605. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71606. }
  71607. // Front
  71608. engine.setDepthFunctionToLess();
  71609. this._scene.resetCachedMaterial();
  71610. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71611. this._colorShader.bind(worldMatrix);
  71612. // Draw order
  71613. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71614. }
  71615. this._colorShader.unbind();
  71616. engine.setDepthFunctionToLessOrEqual();
  71617. engine.setDepthWrite(true);
  71618. };
  71619. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71620. this._prepareRessources();
  71621. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71622. return;
  71623. }
  71624. var engine = this._scene.getEngine();
  71625. engine.setDepthWrite(false);
  71626. engine.setColorWrite(false);
  71627. this._colorShader._preBind();
  71628. var boundingBox = mesh._boundingInfo.boundingBox;
  71629. var min = boundingBox.minimum;
  71630. var max = boundingBox.maximum;
  71631. var diff = max.subtract(min);
  71632. var median = min.add(diff.scale(0.5));
  71633. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71634. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71635. .multiply(boundingBox.getWorldMatrix());
  71636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71637. engine.setDepthFunctionToLess();
  71638. this._scene.resetCachedMaterial();
  71639. this._colorShader.bind(worldMatrix);
  71640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71641. this._colorShader.unbind();
  71642. engine.setDepthFunctionToLessOrEqual();
  71643. engine.setDepthWrite(true);
  71644. engine.setColorWrite(true);
  71645. };
  71646. BoundingBoxRenderer.prototype.dispose = function () {
  71647. if (!this._colorShader) {
  71648. return;
  71649. }
  71650. this.renderList.dispose();
  71651. this._colorShader.dispose();
  71652. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71653. if (buffer) {
  71654. buffer.dispose();
  71655. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71656. }
  71657. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71658. };
  71659. return BoundingBoxRenderer;
  71660. }());
  71661. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71662. })(BABYLON || (BABYLON = {}));
  71663. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71664. var BABYLON;
  71665. (function (BABYLON) {
  71666. var MorphTarget = /** @class */ (function () {
  71667. function MorphTarget(name, influence) {
  71668. if (influence === void 0) { influence = 0; }
  71669. this.name = name;
  71670. this.animations = new Array();
  71671. this._positions = null;
  71672. this._normals = null;
  71673. this._tangents = null;
  71674. this.onInfluenceChanged = new BABYLON.Observable();
  71675. this.influence = influence;
  71676. }
  71677. Object.defineProperty(MorphTarget.prototype, "influence", {
  71678. get: function () {
  71679. return this._influence;
  71680. },
  71681. set: function (influence) {
  71682. if (this._influence === influence) {
  71683. return;
  71684. }
  71685. var previous = this._influence;
  71686. this._influence = influence;
  71687. if (this.onInfluenceChanged.hasObservers) {
  71688. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71689. }
  71690. },
  71691. enumerable: true,
  71692. configurable: true
  71693. });
  71694. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71695. get: function () {
  71696. return !!this._positions;
  71697. },
  71698. enumerable: true,
  71699. configurable: true
  71700. });
  71701. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71702. get: function () {
  71703. return !!this._normals;
  71704. },
  71705. enumerable: true,
  71706. configurable: true
  71707. });
  71708. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71709. get: function () {
  71710. return !!this._tangents;
  71711. },
  71712. enumerable: true,
  71713. configurable: true
  71714. });
  71715. MorphTarget.prototype.setPositions = function (data) {
  71716. this._positions = data;
  71717. };
  71718. MorphTarget.prototype.getPositions = function () {
  71719. return this._positions;
  71720. };
  71721. MorphTarget.prototype.setNormals = function (data) {
  71722. this._normals = data;
  71723. };
  71724. MorphTarget.prototype.getNormals = function () {
  71725. return this._normals;
  71726. };
  71727. MorphTarget.prototype.setTangents = function (data) {
  71728. this._tangents = data;
  71729. };
  71730. MorphTarget.prototype.getTangents = function () {
  71731. return this._tangents;
  71732. };
  71733. /**
  71734. * Serializes the current target into a Serialization object.
  71735. * Returns the serialized object.
  71736. */
  71737. MorphTarget.prototype.serialize = function () {
  71738. var serializationObject = {};
  71739. serializationObject.name = this.name;
  71740. serializationObject.influence = this.influence;
  71741. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71742. if (this.hasNormals) {
  71743. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71744. }
  71745. if (this.hasTangents) {
  71746. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71747. }
  71748. // Animations
  71749. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71750. return serializationObject;
  71751. };
  71752. // Statics
  71753. MorphTarget.Parse = function (serializationObject) {
  71754. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71755. result.setPositions(serializationObject.positions);
  71756. if (serializationObject.normals) {
  71757. result.setNormals(serializationObject.normals);
  71758. }
  71759. if (serializationObject.tangents) {
  71760. result.setTangents(serializationObject.tangents);
  71761. }
  71762. // Animations
  71763. if (serializationObject.animations) {
  71764. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71765. var parsedAnimation = serializationObject.animations[animationIndex];
  71766. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71767. }
  71768. }
  71769. return result;
  71770. };
  71771. MorphTarget.FromMesh = function (mesh, name, influence) {
  71772. if (!name) {
  71773. name = mesh.name;
  71774. }
  71775. var result = new MorphTarget(name, influence);
  71776. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71778. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71779. }
  71780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71781. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71782. }
  71783. return result;
  71784. };
  71785. return MorphTarget;
  71786. }());
  71787. BABYLON.MorphTarget = MorphTarget;
  71788. })(BABYLON || (BABYLON = {}));
  71789. //# sourceMappingURL=babylon.morphTarget.js.map
  71790. var BABYLON;
  71791. (function (BABYLON) {
  71792. var MorphTargetManager = /** @class */ (function () {
  71793. function MorphTargetManager(scene) {
  71794. if (scene === void 0) { scene = null; }
  71795. this._targets = new Array();
  71796. this._targetObservable = new Array();
  71797. this._activeTargets = new BABYLON.SmartArray(16);
  71798. this._supportsNormals = false;
  71799. this._supportsTangents = false;
  71800. this._vertexCount = 0;
  71801. this._uniqueId = 0;
  71802. this._tempInfluences = new Array();
  71803. if (!scene) {
  71804. scene = BABYLON.Engine.LastCreatedScene;
  71805. }
  71806. this._scene = scene;
  71807. if (this._scene) {
  71808. this._scene.morphTargetManagers.push(this);
  71809. this._uniqueId = this._scene.getUniqueId();
  71810. }
  71811. }
  71812. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71813. get: function () {
  71814. return this._uniqueId;
  71815. },
  71816. enumerable: true,
  71817. configurable: true
  71818. });
  71819. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71820. get: function () {
  71821. return this._vertexCount;
  71822. },
  71823. enumerable: true,
  71824. configurable: true
  71825. });
  71826. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71827. get: function () {
  71828. return this._supportsNormals;
  71829. },
  71830. enumerable: true,
  71831. configurable: true
  71832. });
  71833. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71834. get: function () {
  71835. return this._supportsTangents;
  71836. },
  71837. enumerable: true,
  71838. configurable: true
  71839. });
  71840. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71841. get: function () {
  71842. return this._targets.length;
  71843. },
  71844. enumerable: true,
  71845. configurable: true
  71846. });
  71847. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71848. get: function () {
  71849. return this._activeTargets.length;
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71855. get: function () {
  71856. return this._influences;
  71857. },
  71858. enumerable: true,
  71859. configurable: true
  71860. });
  71861. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71862. return this._activeTargets.data[index];
  71863. };
  71864. MorphTargetManager.prototype.getTarget = function (index) {
  71865. return this._targets[index];
  71866. };
  71867. MorphTargetManager.prototype.addTarget = function (target) {
  71868. var _this = this;
  71869. this._targets.push(target);
  71870. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71871. _this._syncActiveTargets(needUpdate);
  71872. }));
  71873. this._syncActiveTargets(true);
  71874. };
  71875. MorphTargetManager.prototype.removeTarget = function (target) {
  71876. var index = this._targets.indexOf(target);
  71877. if (index >= 0) {
  71878. this._targets.splice(index, 1);
  71879. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71880. this._syncActiveTargets(true);
  71881. }
  71882. };
  71883. /**
  71884. * Serializes the current manager into a Serialization object.
  71885. * Returns the serialized object.
  71886. */
  71887. MorphTargetManager.prototype.serialize = function () {
  71888. var serializationObject = {};
  71889. serializationObject.id = this.uniqueId;
  71890. serializationObject.targets = [];
  71891. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71892. var target = _a[_i];
  71893. serializationObject.targets.push(target.serialize());
  71894. }
  71895. return serializationObject;
  71896. };
  71897. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71898. var influenceCount = 0;
  71899. this._activeTargets.reset();
  71900. this._supportsNormals = true;
  71901. this._supportsTangents = true;
  71902. this._vertexCount = 0;
  71903. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71904. var target = _a[_i];
  71905. this._activeTargets.push(target);
  71906. this._tempInfluences[influenceCount++] = target.influence;
  71907. var positions = target.getPositions();
  71908. if (positions) {
  71909. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71910. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71911. var vertexCount = positions.length / 3;
  71912. if (this._vertexCount === 0) {
  71913. this._vertexCount = vertexCount;
  71914. }
  71915. else if (this._vertexCount !== vertexCount) {
  71916. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71917. return;
  71918. }
  71919. }
  71920. }
  71921. if (!this._influences || this._influences.length !== influenceCount) {
  71922. this._influences = new Float32Array(influenceCount);
  71923. }
  71924. for (var index = 0; index < influenceCount; index++) {
  71925. this._influences[index] = this._tempInfluences[index];
  71926. }
  71927. if (needUpdate && this._scene) {
  71928. // Flag meshes as dirty to resync with the active targets
  71929. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71930. var mesh = _c[_b];
  71931. if (mesh.morphTargetManager === this) {
  71932. mesh._syncGeometryWithMorphTargetManager();
  71933. }
  71934. }
  71935. }
  71936. };
  71937. // Statics
  71938. MorphTargetManager.Parse = function (serializationObject, scene) {
  71939. var result = new MorphTargetManager(scene);
  71940. result._uniqueId = serializationObject.id;
  71941. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71942. var targetData = _a[_i];
  71943. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71944. }
  71945. return result;
  71946. };
  71947. return MorphTargetManager;
  71948. }());
  71949. BABYLON.MorphTargetManager = MorphTargetManager;
  71950. })(BABYLON || (BABYLON = {}));
  71951. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71952. var BABYLON;
  71953. (function (BABYLON) {
  71954. var Octree = /** @class */ (function () {
  71955. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71956. if (maxDepth === void 0) { maxDepth = 2; }
  71957. this.maxDepth = maxDepth;
  71958. this.dynamicContent = new Array();
  71959. this._maxBlockCapacity = maxBlockCapacity || 64;
  71960. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71961. this._creationFunc = creationFunc;
  71962. }
  71963. // Methods
  71964. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71965. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71966. };
  71967. Octree.prototype.addMesh = function (entry) {
  71968. for (var index = 0; index < this.blocks.length; index++) {
  71969. var block = this.blocks[index];
  71970. block.addEntry(entry);
  71971. }
  71972. };
  71973. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71974. this._selectionContent.reset();
  71975. for (var index = 0; index < this.blocks.length; index++) {
  71976. var block = this.blocks[index];
  71977. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71978. }
  71979. if (allowDuplicate) {
  71980. this._selectionContent.concat(this.dynamicContent);
  71981. }
  71982. else {
  71983. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71984. }
  71985. return this._selectionContent;
  71986. };
  71987. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71988. this._selectionContent.reset();
  71989. for (var index = 0; index < this.blocks.length; index++) {
  71990. var block = this.blocks[index];
  71991. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71992. }
  71993. if (allowDuplicate) {
  71994. this._selectionContent.concat(this.dynamicContent);
  71995. }
  71996. else {
  71997. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71998. }
  71999. return this._selectionContent;
  72000. };
  72001. Octree.prototype.intersectsRay = function (ray) {
  72002. this._selectionContent.reset();
  72003. for (var index = 0; index < this.blocks.length; index++) {
  72004. var block = this.blocks[index];
  72005. block.intersectsRay(ray, this._selectionContent);
  72006. }
  72007. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72008. return this._selectionContent;
  72009. };
  72010. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  72011. target.blocks = new Array();
  72012. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  72013. // Segmenting space
  72014. for (var x = 0; x < 2; x++) {
  72015. for (var y = 0; y < 2; y++) {
  72016. for (var z = 0; z < 2; z++) {
  72017. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72018. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72019. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72020. block.addEntries(entries);
  72021. target.blocks.push(block);
  72022. }
  72023. }
  72024. }
  72025. };
  72026. Octree.CreationFuncForMeshes = function (entry, block) {
  72027. var boundingInfo = entry.getBoundingInfo();
  72028. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72029. block.entries.push(entry);
  72030. }
  72031. };
  72032. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72033. var boundingInfo = entry.getBoundingInfo();
  72034. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72035. block.entries.push(entry);
  72036. }
  72037. };
  72038. return Octree;
  72039. }());
  72040. BABYLON.Octree = Octree;
  72041. })(BABYLON || (BABYLON = {}));
  72042. //# sourceMappingURL=babylon.octree.js.map
  72043. var BABYLON;
  72044. (function (BABYLON) {
  72045. var OctreeBlock = /** @class */ (function () {
  72046. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72047. this.entries = new Array();
  72048. this._boundingVectors = new Array();
  72049. this._capacity = capacity;
  72050. this._depth = depth;
  72051. this._maxDepth = maxDepth;
  72052. this._creationFunc = creationFunc;
  72053. this._minPoint = minPoint;
  72054. this._maxPoint = maxPoint;
  72055. this._boundingVectors.push(minPoint.clone());
  72056. this._boundingVectors.push(maxPoint.clone());
  72057. this._boundingVectors.push(minPoint.clone());
  72058. this._boundingVectors[2].x = maxPoint.x;
  72059. this._boundingVectors.push(minPoint.clone());
  72060. this._boundingVectors[3].y = maxPoint.y;
  72061. this._boundingVectors.push(minPoint.clone());
  72062. this._boundingVectors[4].z = maxPoint.z;
  72063. this._boundingVectors.push(maxPoint.clone());
  72064. this._boundingVectors[5].z = minPoint.z;
  72065. this._boundingVectors.push(maxPoint.clone());
  72066. this._boundingVectors[6].x = minPoint.x;
  72067. this._boundingVectors.push(maxPoint.clone());
  72068. this._boundingVectors[7].y = minPoint.y;
  72069. }
  72070. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72071. // Property
  72072. get: function () {
  72073. return this._capacity;
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72079. get: function () {
  72080. return this._minPoint;
  72081. },
  72082. enumerable: true,
  72083. configurable: true
  72084. });
  72085. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72086. get: function () {
  72087. return this._maxPoint;
  72088. },
  72089. enumerable: true,
  72090. configurable: true
  72091. });
  72092. // Methods
  72093. OctreeBlock.prototype.addEntry = function (entry) {
  72094. if (this.blocks) {
  72095. for (var index = 0; index < this.blocks.length; index++) {
  72096. var block = this.blocks[index];
  72097. block.addEntry(entry);
  72098. }
  72099. return;
  72100. }
  72101. this._creationFunc(entry, this);
  72102. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72103. this.createInnerBlocks();
  72104. }
  72105. };
  72106. OctreeBlock.prototype.addEntries = function (entries) {
  72107. for (var index = 0; index < entries.length; index++) {
  72108. var mesh = entries[index];
  72109. this.addEntry(mesh);
  72110. }
  72111. };
  72112. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72113. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72114. if (this.blocks) {
  72115. for (var index = 0; index < this.blocks.length; index++) {
  72116. var block = this.blocks[index];
  72117. block.select(frustumPlanes, selection, allowDuplicate);
  72118. }
  72119. return;
  72120. }
  72121. if (allowDuplicate) {
  72122. selection.concat(this.entries);
  72123. }
  72124. else {
  72125. selection.concatWithNoDuplicate(this.entries);
  72126. }
  72127. }
  72128. };
  72129. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72130. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72131. if (this.blocks) {
  72132. for (var index = 0; index < this.blocks.length; index++) {
  72133. var block = this.blocks[index];
  72134. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72135. }
  72136. return;
  72137. }
  72138. if (allowDuplicate) {
  72139. selection.concat(this.entries);
  72140. }
  72141. else {
  72142. selection.concatWithNoDuplicate(this.entries);
  72143. }
  72144. }
  72145. };
  72146. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72147. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72148. if (this.blocks) {
  72149. for (var index = 0; index < this.blocks.length; index++) {
  72150. var block = this.blocks[index];
  72151. block.intersectsRay(ray, selection);
  72152. }
  72153. return;
  72154. }
  72155. selection.concatWithNoDuplicate(this.entries);
  72156. }
  72157. };
  72158. OctreeBlock.prototype.createInnerBlocks = function () {
  72159. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72160. };
  72161. return OctreeBlock;
  72162. }());
  72163. BABYLON.OctreeBlock = OctreeBlock;
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.octreeBlock.js.map
  72166. var BABYLON;
  72167. (function (BABYLON) {
  72168. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72169. __extends(VRDistortionCorrectionPostProcess, _super);
  72170. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72171. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72172. 'LensCenter',
  72173. 'Scale',
  72174. 'ScaleIn',
  72175. 'HmdWarpParam'
  72176. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72177. _this._isRightEye = isRightEye;
  72178. _this._distortionFactors = vrMetrics.distortionK;
  72179. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72180. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72181. _this.adaptScaleToCurrentViewport = true;
  72182. _this.onSizeChangedObservable.add(function () {
  72183. _this.aspectRatio = _this.width * .5 / _this.height;
  72184. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72185. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72186. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72187. });
  72188. _this.onApplyObservable.add(function (effect) {
  72189. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72190. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72191. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72192. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72193. });
  72194. return _this;
  72195. }
  72196. return VRDistortionCorrectionPostProcess;
  72197. }(BABYLON.PostProcess));
  72198. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72199. })(BABYLON || (BABYLON = {}));
  72200. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72201. var BABYLON;
  72202. (function (BABYLON) {
  72203. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72204. __extends(AnaglyphPostProcess, _super);
  72205. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72206. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72207. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72208. _this.onApplyObservable.add(function (effect) {
  72209. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72210. });
  72211. return _this;
  72212. }
  72213. return AnaglyphPostProcess;
  72214. }(BABYLON.PostProcess));
  72215. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72216. })(BABYLON || (BABYLON = {}));
  72217. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72218. var BABYLON;
  72219. (function (BABYLON) {
  72220. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72221. __extends(StereoscopicInterlacePostProcess, _super);
  72222. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72223. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72224. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72225. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72226. _this.onSizeChangedObservable.add(function () {
  72227. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72228. });
  72229. _this.onApplyObservable.add(function (effect) {
  72230. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72231. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72232. });
  72233. return _this;
  72234. }
  72235. return StereoscopicInterlacePostProcess;
  72236. }(BABYLON.PostProcess));
  72237. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72238. })(BABYLON || (BABYLON = {}));
  72239. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72240. var BABYLON;
  72241. (function (BABYLON) {
  72242. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72243. function FreeCameraDeviceOrientationInput() {
  72244. var _this = this;
  72245. this._screenOrientationAngle = 0;
  72246. this._screenQuaternion = new BABYLON.Quaternion();
  72247. this._alpha = 0;
  72248. this._beta = 0;
  72249. this._gamma = 0;
  72250. this._orientationChanged = function () {
  72251. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72252. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72253. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72254. };
  72255. this._deviceOrientation = function (evt) {
  72256. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72257. _this._beta = evt.beta !== null ? evt.beta : 0;
  72258. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72259. };
  72260. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72261. this._orientationChanged();
  72262. }
  72263. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72264. get: function () {
  72265. return this._camera;
  72266. },
  72267. set: function (camera) {
  72268. this._camera = camera;
  72269. if (this._camera != null && !this._camera.rotationQuaternion) {
  72270. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72271. }
  72272. },
  72273. enumerable: true,
  72274. configurable: true
  72275. });
  72276. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72277. window.addEventListener("orientationchange", this._orientationChanged);
  72278. window.addEventListener("deviceorientation", this._deviceOrientation);
  72279. //In certain cases, the attach control is called AFTER orientation was changed,
  72280. //So this is needed.
  72281. this._orientationChanged();
  72282. };
  72283. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72284. window.removeEventListener("orientationchange", this._orientationChanged);
  72285. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72286. };
  72287. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72288. //if no device orientation provided, don't update the rotation.
  72289. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72290. if (!this._alpha)
  72291. return;
  72292. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72293. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72294. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72295. //Mirror on XY Plane
  72296. this._camera.rotationQuaternion.z *= -1;
  72297. this._camera.rotationQuaternion.w *= -1;
  72298. };
  72299. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72300. return "FreeCameraDeviceOrientationInput";
  72301. };
  72302. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72303. return "deviceOrientation";
  72304. };
  72305. return FreeCameraDeviceOrientationInput;
  72306. }());
  72307. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72308. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72309. })(BABYLON || (BABYLON = {}));
  72310. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72311. var BABYLON;
  72312. (function (BABYLON) {
  72313. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72314. function ArcRotateCameraVRDeviceOrientationInput() {
  72315. this.alphaCorrection = 1;
  72316. this.betaCorrection = 1;
  72317. this.gammaCorrection = 1;
  72318. this._alpha = 0;
  72319. this._gamma = 0;
  72320. this._dirty = false;
  72321. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72322. }
  72323. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72324. this.camera.attachControl(element, noPreventDefault);
  72325. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72326. };
  72327. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72328. if (evt.alpha !== null) {
  72329. this._alpha = +evt.alpha | 0;
  72330. }
  72331. if (evt.gamma !== null) {
  72332. this._gamma = +evt.gamma | 0;
  72333. }
  72334. this._dirty = true;
  72335. };
  72336. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72337. if (this._dirty) {
  72338. this._dirty = false;
  72339. if (this._gamma < 0) {
  72340. this._gamma = 180 + this._gamma;
  72341. }
  72342. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72343. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72344. }
  72345. };
  72346. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72347. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72348. };
  72349. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72350. return "ArcRotateCameraVRDeviceOrientationInput";
  72351. };
  72352. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72353. return "VRDeviceOrientation";
  72354. };
  72355. return ArcRotateCameraVRDeviceOrientationInput;
  72356. }());
  72357. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72358. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72359. })(BABYLON || (BABYLON = {}));
  72360. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72361. var BABYLON;
  72362. (function (BABYLON) {
  72363. var VRCameraMetrics = /** @class */ (function () {
  72364. function VRCameraMetrics() {
  72365. this.compensateDistortion = true;
  72366. }
  72367. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72368. get: function () {
  72369. return this.hResolution / (2 * this.vResolution);
  72370. },
  72371. enumerable: true,
  72372. configurable: true
  72373. });
  72374. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72375. get: function () {
  72376. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72377. },
  72378. enumerable: true,
  72379. configurable: true
  72380. });
  72381. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72382. get: function () {
  72383. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72384. var h = (4 * meters) / this.hScreenSize;
  72385. return BABYLON.Matrix.Translation(h, 0, 0);
  72386. },
  72387. enumerable: true,
  72388. configurable: true
  72389. });
  72390. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72391. get: function () {
  72392. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72393. var h = (4 * meters) / this.hScreenSize;
  72394. return BABYLON.Matrix.Translation(-h, 0, 0);
  72395. },
  72396. enumerable: true,
  72397. configurable: true
  72398. });
  72399. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72400. get: function () {
  72401. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72402. },
  72403. enumerable: true,
  72404. configurable: true
  72405. });
  72406. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72407. get: function () {
  72408. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72409. },
  72410. enumerable: true,
  72411. configurable: true
  72412. });
  72413. VRCameraMetrics.GetDefault = function () {
  72414. var result = new VRCameraMetrics();
  72415. result.hResolution = 1280;
  72416. result.vResolution = 800;
  72417. result.hScreenSize = 0.149759993;
  72418. result.vScreenSize = 0.0935999975;
  72419. result.vScreenCenter = 0.0467999987;
  72420. result.eyeToScreenDistance = 0.0410000011;
  72421. result.lensSeparationDistance = 0.0635000020;
  72422. result.interpupillaryDistance = 0.0640000030;
  72423. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72424. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72425. result.postProcessScaleFactor = 1.714605507808412;
  72426. result.lensCenterOffset = 0.151976421;
  72427. return result;
  72428. };
  72429. return VRCameraMetrics;
  72430. }());
  72431. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72432. })(BABYLON || (BABYLON = {}));
  72433. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72434. var BABYLON;
  72435. (function (BABYLON) {
  72436. var WebVRFreeCamera = /** @class */ (function (_super) {
  72437. __extends(WebVRFreeCamera, _super);
  72438. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72439. if (webVROptions === void 0) { webVROptions = {}; }
  72440. var _this = _super.call(this, name, position, scene) || this;
  72441. _this.webVROptions = webVROptions;
  72442. _this._vrDevice = null;
  72443. _this.rawPose = null;
  72444. _this._specsVersion = "1.1";
  72445. _this._attached = false;
  72446. _this._descendants = [];
  72447. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72448. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72449. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72450. _this._standingMatrix = null;
  72451. // Represents device position and rotation in babylon space
  72452. _this.devicePosition = BABYLON.Vector3.Zero();
  72453. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72454. _this.deviceScaleFactor = 1;
  72455. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72456. _this._worldToDevice = BABYLON.Matrix.Identity();
  72457. _this.controllers = [];
  72458. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72459. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72460. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72461. _this._defaultHeight = 0;
  72462. _this.deviceDistanceToRoomGround = function () {
  72463. if (_this._standingMatrix) {
  72464. // Add standing matrix offset to get real offset from ground in room
  72465. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72466. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72467. }
  72468. else {
  72469. return _this._defaultHeight;
  72470. }
  72471. };
  72472. _this.useStandingMatrix = function (callback) {
  72473. if (callback === void 0) { callback = function (bool) { }; }
  72474. // Use standing matrix if availible
  72475. if (!navigator || !navigator.getVRDisplays) {
  72476. callback(false);
  72477. }
  72478. else {
  72479. navigator.getVRDisplays().then(function (displays) {
  72480. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72481. callback(false);
  72482. }
  72483. else {
  72484. _this._standingMatrix = new BABYLON.Matrix();
  72485. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72486. if (!_this.getScene().useRightHandedSystem) {
  72487. [2, 6, 8, 9, 14].forEach(function (num) {
  72488. if (_this._standingMatrix) {
  72489. _this._standingMatrix.m[num] *= -1;
  72490. }
  72491. });
  72492. }
  72493. callback(true);
  72494. }
  72495. });
  72496. }
  72497. };
  72498. _this._workingVector = BABYLON.Vector3.Zero();
  72499. _this._oneVector = BABYLON.Vector3.One();
  72500. _this._workingMatrix = BABYLON.Matrix.Identity();
  72501. _this._cache.position = BABYLON.Vector3.Zero();
  72502. if (webVROptions.defaultHeight) {
  72503. _this._defaultHeight = webVROptions.defaultHeight;
  72504. _this.position.y = _this._defaultHeight;
  72505. }
  72506. _this.minZ = 0.1;
  72507. //legacy support - the compensation boolean was removed.
  72508. if (arguments.length === 5) {
  72509. _this.webVROptions = arguments[4];
  72510. }
  72511. // default webVR options
  72512. if (_this.webVROptions.trackPosition == undefined) {
  72513. _this.webVROptions.trackPosition = true;
  72514. }
  72515. if (_this.webVROptions.controllerMeshes == undefined) {
  72516. _this.webVROptions.controllerMeshes = true;
  72517. }
  72518. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72519. _this.webVROptions.defaultLightingOnControllers = true;
  72520. }
  72521. _this.rotationQuaternion = new BABYLON.Quaternion();
  72522. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72523. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72524. }
  72525. //enable VR
  72526. var engine = _this.getEngine();
  72527. _this._onVREnabled = function (success) { if (success) {
  72528. _this.initControllers();
  72529. } };
  72530. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72531. engine.initWebVR().add(function (event) {
  72532. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72533. return;
  72534. }
  72535. _this._vrDevice = event.vrDisplay;
  72536. //reset the rig parameters.
  72537. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72538. if (_this._attached) {
  72539. _this.getEngine().enableVR();
  72540. }
  72541. });
  72542. if (typeof (VRFrameData) !== "undefined")
  72543. _this._frameData = new VRFrameData();
  72544. /**
  72545. * The idea behind the following lines:
  72546. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72547. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72548. * the second will not show it correctly.
  72549. *
  72550. * To solve this - each object that has the camera as parent will be added to a protected array.
  72551. * When the rig camera renders, it will take this array and set all of those to be its children.
  72552. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72553. * Amazing!
  72554. */
  72555. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72556. if (camera.parent === _this && _this.rigParenting) {
  72557. _this._descendants = _this.getDescendants(true, function (n) {
  72558. // don't take the cameras or the controllers!
  72559. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72560. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72561. return !isController && !isRigCamera;
  72562. });
  72563. _this._descendants.forEach(function (node) {
  72564. node.parent = camera;
  72565. });
  72566. }
  72567. });
  72568. scene.onAfterCameraRenderObservable.add(function (camera) {
  72569. if (camera.parent === _this && _this.rigParenting) {
  72570. _this._descendants.forEach(function (node) {
  72571. node.parent = _this;
  72572. });
  72573. }
  72574. });
  72575. return _this;
  72576. }
  72577. WebVRFreeCamera.prototype.dispose = function () {
  72578. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72579. _super.prototype.dispose.call(this);
  72580. };
  72581. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72582. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72583. var gp = _a[_i];
  72584. if (gp.hand === name) {
  72585. return gp;
  72586. }
  72587. }
  72588. return null;
  72589. };
  72590. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72591. get: function () {
  72592. if (!this._leftController) {
  72593. this._leftController = this.getControllerByName("left");
  72594. }
  72595. return this._leftController;
  72596. },
  72597. enumerable: true,
  72598. configurable: true
  72599. });
  72600. ;
  72601. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72602. get: function () {
  72603. if (!this._rightController) {
  72604. this._rightController = this.getControllerByName("right");
  72605. }
  72606. return this._rightController;
  72607. },
  72608. enumerable: true,
  72609. configurable: true
  72610. });
  72611. ;
  72612. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72613. if (length === void 0) { length = 100; }
  72614. if (this.leftCamera) {
  72615. // Use left eye to avoid computation to compute center on every call
  72616. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72617. }
  72618. else {
  72619. return _super.prototype.getForwardRay.call(this, length);
  72620. }
  72621. };
  72622. WebVRFreeCamera.prototype._checkInputs = function () {
  72623. if (this._vrDevice && this._vrDevice.isPresenting) {
  72624. this._vrDevice.getFrameData(this._frameData);
  72625. this.updateFromDevice(this._frameData.pose);
  72626. }
  72627. _super.prototype._checkInputs.call(this);
  72628. };
  72629. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72630. if (poseData && poseData.orientation) {
  72631. this.rawPose = poseData;
  72632. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72633. if (this.getScene().useRightHandedSystem) {
  72634. this._deviceRoomRotationQuaternion.z *= -1;
  72635. this._deviceRoomRotationQuaternion.w *= -1;
  72636. }
  72637. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72638. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72639. if (this.getScene().useRightHandedSystem) {
  72640. this._deviceRoomPosition.z *= -1;
  72641. }
  72642. }
  72643. }
  72644. };
  72645. /**
  72646. * WebVR's attach control will start broadcasting frames to the device.
  72647. * Note that in certain browsers (chrome for example) this function must be called
  72648. * within a user-interaction callback. Example:
  72649. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72650. *
  72651. * @param {HTMLElement} element
  72652. * @param {boolean} [noPreventDefault]
  72653. *
  72654. * @memberOf WebVRFreeCamera
  72655. */
  72656. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72657. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72658. this._attached = true;
  72659. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72660. if (this._vrDevice) {
  72661. this.getEngine().enableVR();
  72662. }
  72663. };
  72664. WebVRFreeCamera.prototype.detachControl = function (element) {
  72665. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72666. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72667. _super.prototype.detachControl.call(this, element);
  72668. this._attached = false;
  72669. this.getEngine().disableVR();
  72670. };
  72671. WebVRFreeCamera.prototype.getClassName = function () {
  72672. return "WebVRFreeCamera";
  72673. };
  72674. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72675. //uses the vrDisplay's "resetPose()".
  72676. //pitch and roll won't be affected.
  72677. this._vrDevice.resetPose();
  72678. };
  72679. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72680. var camLeft = this._rigCameras[0];
  72681. var camRight = this._rigCameras[1];
  72682. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72683. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72684. camLeft.position.copyFrom(this._deviceRoomPosition);
  72685. camRight.position.copyFrom(this._deviceRoomPosition);
  72686. };
  72687. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72688. var _this = this;
  72689. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72690. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72691. if (!this.updateCacheCalled) {
  72692. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72693. this.updateCacheCalled = true;
  72694. this.update();
  72695. }
  72696. // Set working vector to the device position in room space rotated by the new rotation
  72697. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72698. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72699. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72700. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72701. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72702. // Add translation from anchor position
  72703. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72704. this._workingVector.addInPlace(this.position);
  72705. this._workingVector.subtractInPlace(this._cache.position);
  72706. this._deviceToWorld.setTranslation(this._workingVector);
  72707. // Set an inverted matrix to be used when updating the camera
  72708. this._deviceToWorld.invertToRef(this._worldToDevice);
  72709. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72710. this.controllers.forEach(function (controller) {
  72711. controller._deviceToWorld = _this._deviceToWorld;
  72712. controller.update();
  72713. });
  72714. }
  72715. if (!ignoreParentClass) {
  72716. _super.prototype._updateCache.call(this);
  72717. }
  72718. this.updateCacheCalled = false;
  72719. };
  72720. WebVRFreeCamera.prototype.update = function () {
  72721. // Get current device position in babylon world
  72722. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72723. // Get current device rotation in babylon world
  72724. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72725. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72726. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72727. _super.prototype.update.call(this);
  72728. };
  72729. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72730. return BABYLON.Matrix.Identity();
  72731. };
  72732. /**
  72733. * This function is called by the two RIG cameras.
  72734. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72735. */
  72736. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72737. var _this = this;
  72738. //WebVR 1.1
  72739. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72740. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72741. if (!this.getScene().useRightHandedSystem) {
  72742. [2, 6, 8, 9, 14].forEach(function (num) {
  72743. _this._webvrViewMatrix.m[num] *= -1;
  72744. });
  72745. }
  72746. // update the camera rotation matrix
  72747. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72748. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72749. // Computing target and final matrix
  72750. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72751. var parentCamera = this._cameraRigParams["parentCamera"];
  72752. // should the view matrix be updated with scale and position offset?
  72753. if (parentCamera.deviceScaleFactor !== 1) {
  72754. this._webvrViewMatrix.invert();
  72755. // scale the position, if set
  72756. if (parentCamera.deviceScaleFactor) {
  72757. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72758. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72759. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72760. }
  72761. this._webvrViewMatrix.invert();
  72762. }
  72763. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72764. return this._webvrViewMatrix;
  72765. };
  72766. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72767. var _this = this;
  72768. var parentCamera = this.parent;
  72769. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72770. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72771. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72772. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72773. //babylon compatible matrix
  72774. if (!this.getScene().useRightHandedSystem) {
  72775. [8, 9, 10, 11].forEach(function (num) {
  72776. _this._projectionMatrix.m[num] *= -1;
  72777. });
  72778. }
  72779. return this._projectionMatrix;
  72780. };
  72781. WebVRFreeCamera.prototype.initControllers = function () {
  72782. var _this = this;
  72783. this.controllers = [];
  72784. var manager = this.getScene().gamepadManager;
  72785. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72786. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72787. var webVrController = gamepad;
  72788. if (webVrController.defaultModel) {
  72789. webVrController.defaultModel.setEnabled(false);
  72790. }
  72791. if (webVrController.hand === "right") {
  72792. _this._rightController = null;
  72793. }
  72794. if (webVrController.hand === "left") {
  72795. _this._rightController = null;
  72796. }
  72797. var controllerIndex = _this.controllers.indexOf(webVrController);
  72798. if (controllerIndex !== -1) {
  72799. _this.controllers.splice(controllerIndex, 1);
  72800. }
  72801. }
  72802. });
  72803. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72804. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72805. var webVrController_1 = gamepad;
  72806. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72807. if (_this.webVROptions.controllerMeshes) {
  72808. if (webVrController_1.defaultModel) {
  72809. webVrController_1.defaultModel.setEnabled(true);
  72810. }
  72811. else {
  72812. // Load the meshes
  72813. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72814. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72815. if (_this.webVROptions.defaultLightingOnControllers) {
  72816. if (!_this._lightOnControllers) {
  72817. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72818. }
  72819. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72820. var children = mesh.getChildren();
  72821. if (children.length !== 0) {
  72822. children.forEach(function (mesh) {
  72823. light.includedOnlyMeshes.push(mesh);
  72824. activateLightOnSubMeshes_1(mesh, light);
  72825. });
  72826. }
  72827. };
  72828. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72829. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72830. }
  72831. });
  72832. }
  72833. }
  72834. webVrController_1.attachToPoseControlledCamera(_this);
  72835. // since this is async - sanity check. Is the controller already stored?
  72836. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72837. //add to the controllers array
  72838. _this.controllers.push(webVrController_1);
  72839. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72840. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72841. // So we're overriding setting left & right manually to be sure
  72842. var firstViveWandDetected = false;
  72843. for (var i = 0; i < _this.controllers.length; i++) {
  72844. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72845. if (!firstViveWandDetected) {
  72846. firstViveWandDetected = true;
  72847. _this.controllers[i].hand = "left";
  72848. }
  72849. else {
  72850. _this.controllers[i].hand = "right";
  72851. }
  72852. }
  72853. }
  72854. //did we find enough controllers? Great! let the developer know.
  72855. if (_this.controllers.length >= 2) {
  72856. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72857. }
  72858. }
  72859. }
  72860. });
  72861. };
  72862. return WebVRFreeCamera;
  72863. }(BABYLON.FreeCamera));
  72864. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72865. })(BABYLON || (BABYLON = {}));
  72866. //# sourceMappingURL=babylon.webVRCamera.js.map
  72867. var BABYLON;
  72868. (function (BABYLON) {
  72869. // We're mainly based on the logic defined into the FreeCamera code
  72870. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72871. __extends(DeviceOrientationCamera, _super);
  72872. function DeviceOrientationCamera(name, position, scene) {
  72873. var _this = _super.call(this, name, position, scene) || this;
  72874. _this._quaternionCache = new BABYLON.Quaternion();
  72875. _this.inputs.addDeviceOrientation();
  72876. return _this;
  72877. }
  72878. DeviceOrientationCamera.prototype.getClassName = function () {
  72879. return "DeviceOrientationCamera";
  72880. };
  72881. DeviceOrientationCamera.prototype._checkInputs = function () {
  72882. _super.prototype._checkInputs.call(this);
  72883. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72884. if (this._initialQuaternion) {
  72885. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72886. }
  72887. };
  72888. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72889. var _this = this;
  72890. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72891. //can only work if this camera has a rotation quaternion already.
  72892. if (!this.rotationQuaternion)
  72893. return;
  72894. if (!this._initialQuaternion) {
  72895. this._initialQuaternion = new BABYLON.Quaternion();
  72896. }
  72897. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72898. ['x', 'y', 'z'].forEach(function (axisName) {
  72899. if (!axis[axisName]) {
  72900. _this._initialQuaternion[axisName] = 0;
  72901. }
  72902. else {
  72903. _this._initialQuaternion[axisName] *= -1;
  72904. }
  72905. });
  72906. this._initialQuaternion.normalize();
  72907. //force rotation update
  72908. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72909. };
  72910. return DeviceOrientationCamera;
  72911. }(BABYLON.FreeCamera));
  72912. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72913. })(BABYLON || (BABYLON = {}));
  72914. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72915. var BABYLON;
  72916. (function (BABYLON) {
  72917. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72918. __extends(VRDeviceOrientationFreeCamera, _super);
  72919. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72920. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72921. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72922. var _this = _super.call(this, name, position, scene) || this;
  72923. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72924. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72925. return _this;
  72926. }
  72927. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72928. return "VRDeviceOrientationFreeCamera";
  72929. };
  72930. return VRDeviceOrientationFreeCamera;
  72931. }(BABYLON.DeviceOrientationCamera));
  72932. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72933. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72934. __extends(VRDeviceOrientationGamepadCamera, _super);
  72935. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72936. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72937. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72938. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72939. _this.inputs.addGamepad();
  72940. return _this;
  72941. }
  72942. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72943. return "VRDeviceOrientationGamepadCamera";
  72944. };
  72945. return VRDeviceOrientationGamepadCamera;
  72946. }(VRDeviceOrientationFreeCamera));
  72947. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72948. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72949. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72950. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72951. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72952. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72953. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72954. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72955. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72956. _this.inputs.addVRDeviceOrientation();
  72957. return _this;
  72958. }
  72959. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72960. return "VRDeviceOrientationArcRotateCamera";
  72961. };
  72962. return VRDeviceOrientationArcRotateCamera;
  72963. }(BABYLON.ArcRotateCamera));
  72964. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72965. })(BABYLON || (BABYLON = {}));
  72966. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72967. var BABYLON;
  72968. (function (BABYLON) {
  72969. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72970. __extends(AnaglyphFreeCamera, _super);
  72971. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72972. var _this = _super.call(this, name, position, scene) || this;
  72973. _this.interaxialDistance = interaxialDistance;
  72974. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72975. return _this;
  72976. }
  72977. AnaglyphFreeCamera.prototype.getClassName = function () {
  72978. return "AnaglyphFreeCamera";
  72979. };
  72980. return AnaglyphFreeCamera;
  72981. }(BABYLON.FreeCamera));
  72982. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72983. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72984. __extends(AnaglyphArcRotateCamera, _super);
  72985. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72986. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72987. _this.interaxialDistance = interaxialDistance;
  72988. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72989. return _this;
  72990. }
  72991. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72992. return "AnaglyphArcRotateCamera";
  72993. };
  72994. return AnaglyphArcRotateCamera;
  72995. }(BABYLON.ArcRotateCamera));
  72996. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72997. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72998. __extends(AnaglyphGamepadCamera, _super);
  72999. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73000. var _this = _super.call(this, name, position, scene) || this;
  73001. _this.interaxialDistance = interaxialDistance;
  73002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73003. return _this;
  73004. }
  73005. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73006. return "AnaglyphGamepadCamera";
  73007. };
  73008. return AnaglyphGamepadCamera;
  73009. }(BABYLON.GamepadCamera));
  73010. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73011. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73012. __extends(AnaglyphUniversalCamera, _super);
  73013. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73014. var _this = _super.call(this, name, position, scene) || this;
  73015. _this.interaxialDistance = interaxialDistance;
  73016. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73017. return _this;
  73018. }
  73019. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73020. return "AnaglyphUniversalCamera";
  73021. };
  73022. return AnaglyphUniversalCamera;
  73023. }(BABYLON.UniversalCamera));
  73024. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73025. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73026. __extends(StereoscopicFreeCamera, _super);
  73027. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73028. var _this = _super.call(this, name, position, scene) || this;
  73029. _this.interaxialDistance = interaxialDistance;
  73030. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73031. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73032. return _this;
  73033. }
  73034. StereoscopicFreeCamera.prototype.getClassName = function () {
  73035. return "StereoscopicFreeCamera";
  73036. };
  73037. return StereoscopicFreeCamera;
  73038. }(BABYLON.FreeCamera));
  73039. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73040. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73041. __extends(StereoscopicArcRotateCamera, _super);
  73042. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73043. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73044. _this.interaxialDistance = interaxialDistance;
  73045. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73046. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73047. return _this;
  73048. }
  73049. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73050. return "StereoscopicArcRotateCamera";
  73051. };
  73052. return StereoscopicArcRotateCamera;
  73053. }(BABYLON.ArcRotateCamera));
  73054. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73055. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73056. __extends(StereoscopicGamepadCamera, _super);
  73057. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73058. var _this = _super.call(this, name, position, scene) || this;
  73059. _this.interaxialDistance = interaxialDistance;
  73060. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73061. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73062. return _this;
  73063. }
  73064. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73065. return "StereoscopicGamepadCamera";
  73066. };
  73067. return StereoscopicGamepadCamera;
  73068. }(BABYLON.GamepadCamera));
  73069. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73070. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73071. __extends(StereoscopicUniversalCamera, _super);
  73072. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73073. var _this = _super.call(this, name, position, scene) || this;
  73074. _this.interaxialDistance = interaxialDistance;
  73075. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73076. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73077. return _this;
  73078. }
  73079. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73080. return "StereoscopicUniversalCamera";
  73081. };
  73082. return StereoscopicUniversalCamera;
  73083. }(BABYLON.UniversalCamera));
  73084. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73085. })(BABYLON || (BABYLON = {}));
  73086. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73087. var BABYLON;
  73088. (function (BABYLON) {
  73089. var VRExperienceHelper = /** @class */ (function () {
  73090. function VRExperienceHelper(scene, webVROptions) {
  73091. if (webVROptions === void 0) { webVROptions = {}; }
  73092. var _this = this;
  73093. this.webVROptions = webVROptions;
  73094. // Can the system support WebVR, even if a headset isn't plugged in?
  73095. this._webVRsupported = false;
  73096. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73097. this._webVRready = false;
  73098. // Are we waiting for the requestPresent callback to complete?
  73099. this._webVRrequesting = false;
  73100. // Are we presenting to the headset right now?
  73101. this._webVRpresenting = false;
  73102. // Are we presenting in the fullscreen fallback?
  73103. this._fullscreenVRpresenting = false;
  73104. /**
  73105. * Observable raised when entering VR.
  73106. */
  73107. this.onEnteringVRObservable = new BABYLON.Observable();
  73108. /**
  73109. * Observable raised when exiting VR.
  73110. */
  73111. this.onExitingVRObservable = new BABYLON.Observable();
  73112. /**
  73113. * Observable raised when controller mesh is loaded.
  73114. */
  73115. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73116. this._useCustomVRButton = false;
  73117. this._teleportationRequested = false;
  73118. this._teleportationEnabledOnLeftController = false;
  73119. this._teleportationEnabledOnRightController = false;
  73120. this._interactionsEnabledOnLeftController = false;
  73121. this._interactionsEnabledOnRightController = false;
  73122. this._leftControllerReady = false;
  73123. this._rightControllerReady = false;
  73124. this._floorMeshesCollection = [];
  73125. this._teleportationAllowed = false;
  73126. this._rotationAllowed = true;
  73127. this._teleportationRequestInitiated = false;
  73128. this._teleportationBackRequestInitiated = false;
  73129. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73130. this._rotationRightAsked = false;
  73131. this._rotationLeftAsked = false;
  73132. this._isDefaultTeleportationTarget = true;
  73133. this._teleportationFillColor = "#444444";
  73134. this._teleportationBorderColor = "#FFFFFF";
  73135. this._rotationAngle = 0;
  73136. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73137. this._padSensibilityUp = 0.65;
  73138. this._padSensibilityDown = 0.35;
  73139. /**
  73140. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73141. */
  73142. this.onNewMeshSelected = new BABYLON.Observable();
  73143. /**
  73144. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73145. */
  73146. this.onNewMeshPicked = new BABYLON.Observable();
  73147. /**
  73148. * Observable raised before camera teleportation
  73149. */
  73150. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73151. /**
  73152. * Observable raised after camera teleportation
  73153. */
  73154. this.onAfterCameraTeleport = new BABYLON.Observable();
  73155. /**
  73156. * Observable raised when current selected mesh gets unselected
  73157. */
  73158. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73159. /**
  73160. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73161. */
  73162. this.teleportationEnabled = true;
  73163. this._pointerDownOnMeshAsked = false;
  73164. this._isActionableMesh = false;
  73165. this._teleportationInitialized = false;
  73166. this._interactionsEnabled = false;
  73167. this._interactionsRequested = false;
  73168. this._displayGaze = true;
  73169. this._displayLaserPointer = true;
  73170. this._dpadPressed = true;
  73171. this._onResize = function () {
  73172. _this.moveButtonToBottomRight();
  73173. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73174. _this.exitVR();
  73175. }
  73176. };
  73177. this._onFullscreenChange = function () {
  73178. if (document.fullscreen !== undefined) {
  73179. _this._fullscreenVRpresenting = document.fullscreen;
  73180. }
  73181. else if (document.mozFullScreen !== undefined) {
  73182. _this._fullscreenVRpresenting = document.mozFullScreen;
  73183. }
  73184. else if (document.webkitIsFullScreen !== undefined) {
  73185. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73186. }
  73187. else if (document.msIsFullScreen !== undefined) {
  73188. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73189. }
  73190. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73191. _this.exitVR();
  73192. if (!_this._useCustomVRButton) {
  73193. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73194. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73195. }
  73196. }
  73197. };
  73198. this.beforeRender = function () {
  73199. _this._castRayAndSelectObject();
  73200. };
  73201. this._onNewGamepadConnected = function (gamepad) {
  73202. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73203. if (gamepad.leftStick) {
  73204. gamepad.onleftstickchanged(function (stickValues) {
  73205. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73206. // Listening to classic/xbox gamepad only if no VR controller is active
  73207. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73208. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73209. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73210. _this._checkTeleportWithRay(stickValues);
  73211. _this._checkTeleportBackwards(stickValues);
  73212. }
  73213. }
  73214. });
  73215. }
  73216. if (gamepad.rightStick) {
  73217. gamepad.onrightstickchanged(function (stickValues) {
  73218. if (_this._teleportationInitialized) {
  73219. _this._checkRotate(stickValues);
  73220. }
  73221. });
  73222. }
  73223. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73224. gamepad.onbuttondown(function (buttonPressed) {
  73225. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73226. _this._selectionPointerDown();
  73227. }
  73228. });
  73229. gamepad.onbuttonup(function (buttonPressed) {
  73230. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73231. _this._selectionPointerUp();
  73232. }
  73233. });
  73234. }
  73235. }
  73236. else {
  73237. var webVRController = gamepad;
  73238. _this._tryEnableInteractionOnController(webVRController);
  73239. }
  73240. };
  73241. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  73242. this._tryEnableInteractionOnController = function (webVRController) {
  73243. if (webVRController.hand === "left") {
  73244. _this._leftControllerReady = true;
  73245. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73246. _this._enableInteractionOnController(webVRController);
  73247. }
  73248. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73249. _this._enableTeleportationOnController(webVRController);
  73250. }
  73251. }
  73252. if (webVRController.hand === "right") {
  73253. _this._rightControllerReady = true;
  73254. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73255. _this._enableInteractionOnController(webVRController);
  73256. }
  73257. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73258. _this._enableTeleportationOnController(webVRController);
  73259. }
  73260. }
  73261. };
  73262. this._onNewGamepadDisconnected = function (gamepad) {
  73263. if (gamepad instanceof BABYLON.WebVRController) {
  73264. if (gamepad.hand === "left") {
  73265. _this._interactionsEnabledOnLeftController = false;
  73266. _this._teleportationEnabledOnLeftController = false;
  73267. _this._leftControllerReady = false;
  73268. if (_this._leftLaserPointer) {
  73269. _this._leftLaserPointer.dispose();
  73270. }
  73271. }
  73272. if (gamepad.hand === "right") {
  73273. _this._interactionsEnabledOnRightController = false;
  73274. _this._teleportationEnabledOnRightController = false;
  73275. _this._rightControllerReady = false;
  73276. if (_this._rightLaserPointer) {
  73277. _this._rightLaserPointer.dispose();
  73278. }
  73279. }
  73280. }
  73281. };
  73282. this._workingVector = BABYLON.Vector3.Zero();
  73283. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73284. this._workingMatrix = BABYLON.Matrix.Identity();
  73285. this._scene = scene;
  73286. this._canvas = scene.getEngine().getRenderingCanvas();
  73287. // Parse options
  73288. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73289. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73290. }
  73291. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73292. webVROptions.createDeviceOrientationCamera = true;
  73293. }
  73294. if (webVROptions.defaultHeight === undefined) {
  73295. webVROptions.defaultHeight = 1.7;
  73296. }
  73297. if (webVROptions.useCustomVRButton) {
  73298. this._useCustomVRButton = true;
  73299. if (webVROptions.customVRButton) {
  73300. this._btnVR = webVROptions.customVRButton;
  73301. }
  73302. }
  73303. if (webVROptions.rayLength) {
  73304. this._rayLength = webVROptions.rayLength;
  73305. }
  73306. this._defaultHeight = webVROptions.defaultHeight;
  73307. // Set position
  73308. if (this._scene.activeCamera) {
  73309. this._position = this._scene.activeCamera.position.clone();
  73310. }
  73311. else {
  73312. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73313. }
  73314. // Set non-vr camera
  73315. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73316. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73317. // Copy data from existing camera
  73318. if (this._scene.activeCamera) {
  73319. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73320. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73321. // Set rotation from previous camera
  73322. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73323. var targetCamera = this._scene.activeCamera;
  73324. if (targetCamera.rotationQuaternion) {
  73325. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73326. }
  73327. else {
  73328. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73329. }
  73330. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73331. }
  73332. }
  73333. this._scene.activeCamera = this._deviceOrientationCamera;
  73334. if (this._canvas) {
  73335. this._scene.activeCamera.attachControl(this._canvas);
  73336. }
  73337. }
  73338. else {
  73339. this._existingCamera = this._scene.activeCamera;
  73340. }
  73341. // Create VR cameras
  73342. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73343. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73344. }
  73345. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73346. this._webVRCamera.useStandingMatrix();
  73347. // Create default button
  73348. if (!this._useCustomVRButton) {
  73349. this._btnVR = document.createElement("BUTTON");
  73350. this._btnVR.className = "babylonVRicon";
  73351. this._btnVR.id = "babylonVRiconbtn";
  73352. this._btnVR.title = "Click to switch to VR";
  73353. 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) }";
  73354. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73355. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73356. // css += ".babylonVRicon.vrdisplaysupported { }";
  73357. // css += ".babylonVRicon.vrdisplayready { }";
  73358. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73359. var style = document.createElement('style');
  73360. style.appendChild(document.createTextNode(css));
  73361. document.getElementsByTagName('head')[0].appendChild(style);
  73362. this.moveButtonToBottomRight();
  73363. }
  73364. // VR button click event
  73365. if (this._btnVR) {
  73366. this._btnVR.addEventListener("click", function () {
  73367. if (!_this.isInVRMode) {
  73368. _this.enterVR();
  73369. }
  73370. else {
  73371. _this.exitVR();
  73372. }
  73373. });
  73374. }
  73375. // Window events
  73376. window.addEventListener("resize", this._onResize);
  73377. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73378. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73379. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73380. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73381. // Display vr button when headset is connected
  73382. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73383. this.displayVRButton();
  73384. }
  73385. else {
  73386. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73387. if (e.vrDisplay) {
  73388. _this.displayVRButton();
  73389. }
  73390. });
  73391. }
  73392. // Exiting VR mode using 'ESC' key on desktop
  73393. this._onKeyDown = function (event) {
  73394. if (event.keyCode === 27 && _this.isInVRMode) {
  73395. _this.exitVR();
  73396. }
  73397. };
  73398. document.addEventListener("keydown", this._onKeyDown);
  73399. // Exiting VR mode double tapping the touch screen
  73400. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73401. if (_this.isInVRMode) {
  73402. _this.exitVR();
  73403. if (_this._fullscreenVRpresenting) {
  73404. _this._scene.getEngine().switchFullscreen(true);
  73405. }
  73406. }
  73407. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73408. // Listen for WebVR display changes
  73409. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73410. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73411. this._onVRRequestPresentStart = function () {
  73412. _this._webVRrequesting = true;
  73413. _this.updateButtonVisibility();
  73414. };
  73415. this._onVRRequestPresentComplete = function (success) {
  73416. _this._webVRrequesting = false;
  73417. _this.updateButtonVisibility();
  73418. };
  73419. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73420. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73421. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73422. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73423. scene.onDisposeObservable.add(function () {
  73424. _this.dispose();
  73425. });
  73426. // Gamepad connection events
  73427. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73428. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73429. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73430. this.updateButtonVisibility();
  73431. //create easing functions
  73432. this._circleEase = new BABYLON.CircleEase();
  73433. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73434. }
  73435. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73436. /** Return this.onEnteringVRObservable
  73437. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73438. */
  73439. get: function () {
  73440. return this.onEnteringVRObservable;
  73441. },
  73442. enumerable: true,
  73443. configurable: true
  73444. });
  73445. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73446. /** Return this.onExitingVRObservable
  73447. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73448. */
  73449. get: function () {
  73450. return this.onExitingVRObservable;
  73451. },
  73452. enumerable: true,
  73453. configurable: true
  73454. });
  73455. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73456. /** Return this.onControllerMeshLoadedObservable
  73457. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73458. */
  73459. get: function () {
  73460. return this.onControllerMeshLoadedObservable;
  73461. },
  73462. enumerable: true,
  73463. configurable: true
  73464. });
  73465. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73466. get: function () {
  73467. return this._teleportationTarget;
  73468. },
  73469. set: function (value) {
  73470. if (value) {
  73471. value.name = "teleportationTarget";
  73472. this._isDefaultTeleportationTarget = false;
  73473. this._teleportationTarget = value;
  73474. }
  73475. },
  73476. enumerable: true,
  73477. configurable: true
  73478. });
  73479. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73480. get: function () {
  73481. return this._displayGaze;
  73482. },
  73483. set: function (value) {
  73484. this._displayGaze = value;
  73485. if (!value) {
  73486. this._gazeTracker.isVisible = false;
  73487. }
  73488. },
  73489. enumerable: true,
  73490. configurable: true
  73491. });
  73492. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73493. get: function () {
  73494. return this._displayLaserPointer;
  73495. },
  73496. set: function (value) {
  73497. this._displayLaserPointer = value;
  73498. if (!value) {
  73499. if (this._rightLaserPointer) {
  73500. this._rightLaserPointer.isVisible = false;
  73501. }
  73502. if (this._leftLaserPointer) {
  73503. this._leftLaserPointer.isVisible = false;
  73504. }
  73505. }
  73506. else {
  73507. if (this._rightLaserPointer) {
  73508. this._rightLaserPointer.isVisible = true;
  73509. }
  73510. else if (this._leftLaserPointer) {
  73511. this._leftLaserPointer.isVisible = true;
  73512. }
  73513. }
  73514. },
  73515. enumerable: true,
  73516. configurable: true
  73517. });
  73518. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73519. get: function () {
  73520. return this._deviceOrientationCamera;
  73521. },
  73522. enumerable: true,
  73523. configurable: true
  73524. });
  73525. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73526. // Based on the current WebVR support, returns the current VR camera used
  73527. get: function () {
  73528. if (this._webVRready) {
  73529. return this._webVRCamera;
  73530. }
  73531. else {
  73532. return this._scene.activeCamera;
  73533. }
  73534. },
  73535. enumerable: true,
  73536. configurable: true
  73537. });
  73538. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73539. get: function () {
  73540. return this._webVRCamera;
  73541. },
  73542. enumerable: true,
  73543. configurable: true
  73544. });
  73545. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73546. get: function () {
  73547. return this._vrDeviceOrientationCamera;
  73548. },
  73549. enumerable: true,
  73550. configurable: true
  73551. });
  73552. // Raised when one of the controller has loaded successfully its associated default mesh
  73553. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73554. this._tryEnableInteractionOnController(webVRController);
  73555. try {
  73556. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73557. }
  73558. catch (err) {
  73559. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73560. }
  73561. };
  73562. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73563. /**
  73564. * Gets a value indicating if we are currently in VR mode.
  73565. */
  73566. get: function () {
  73567. return this._webVRpresenting || this._fullscreenVRpresenting;
  73568. },
  73569. enumerable: true,
  73570. configurable: true
  73571. });
  73572. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73573. var vrDisplay = this._scene.getEngine().getVRDevice();
  73574. if (vrDisplay) {
  73575. var wasPresenting = this._webVRpresenting;
  73576. // A VR display is connected
  73577. this._webVRpresenting = vrDisplay.isPresenting;
  73578. if (wasPresenting && !this._webVRpresenting)
  73579. this.exitVR();
  73580. }
  73581. else {
  73582. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73583. }
  73584. this.updateButtonVisibility();
  73585. };
  73586. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73587. this._webVRsupported = eventArgs.vrSupported;
  73588. this._webVRready = !!eventArgs.vrDisplay;
  73589. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73590. this.updateButtonVisibility();
  73591. };
  73592. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73593. if (this._canvas && !this._useCustomVRButton) {
  73594. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73595. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73596. }
  73597. };
  73598. VRExperienceHelper.prototype.displayVRButton = function () {
  73599. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73600. document.body.appendChild(this._btnVR);
  73601. this._btnVRDisplayed = true;
  73602. }
  73603. };
  73604. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73605. if (!this._btnVR || this._useCustomVRButton) {
  73606. return;
  73607. }
  73608. this._btnVR.className = "babylonVRicon";
  73609. if (this.isInVRMode) {
  73610. this._btnVR.className += " vrdisplaypresenting";
  73611. }
  73612. else {
  73613. if (this._webVRready)
  73614. this._btnVR.className += " vrdisplayready";
  73615. if (this._webVRsupported)
  73616. this._btnVR.className += " vrdisplaysupported";
  73617. if (this._webVRrequesting)
  73618. this._btnVR.className += " vrdisplayrequesting";
  73619. }
  73620. };
  73621. /**
  73622. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73623. * Otherwise, will use the fullscreen API.
  73624. */
  73625. VRExperienceHelper.prototype.enterVR = function () {
  73626. if (this.onEnteringVRObservable) {
  73627. try {
  73628. this.onEnteringVRObservable.notifyObservers(this);
  73629. }
  73630. catch (err) {
  73631. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73632. }
  73633. }
  73634. if (this._scene.activeCamera) {
  73635. this._position = this._scene.activeCamera.position.clone();
  73636. // make sure that we return to the last active camera
  73637. this._existingCamera = this._scene.activeCamera;
  73638. }
  73639. if (this._webVRrequesting)
  73640. return;
  73641. // If WebVR is supported and a headset is connected
  73642. if (this._webVRready) {
  73643. if (!this._webVRpresenting) {
  73644. this._webVRCamera.position = this._position;
  73645. this._scene.activeCamera = this._webVRCamera;
  73646. }
  73647. }
  73648. else if (this._vrDeviceOrientationCamera) {
  73649. this._vrDeviceOrientationCamera.position = this._position;
  73650. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73651. this._scene.getEngine().switchFullscreen(true);
  73652. this.updateButtonVisibility();
  73653. }
  73654. if (this._scene.activeCamera && this._canvas) {
  73655. this._scene.activeCamera.attachControl(this._canvas);
  73656. }
  73657. if (this._interactionsEnabled) {
  73658. this._scene.registerBeforeRender(this.beforeRender);
  73659. }
  73660. };
  73661. /**
  73662. * Attempt to exit VR, or fullscreen.
  73663. */
  73664. VRExperienceHelper.prototype.exitVR = function () {
  73665. if (this.onExitingVRObservable) {
  73666. try {
  73667. this.onExitingVRObservable.notifyObservers(this);
  73668. }
  73669. catch (err) {
  73670. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73671. }
  73672. }
  73673. if (this._webVRpresenting) {
  73674. this._scene.getEngine().disableVR();
  73675. }
  73676. if (this._scene.activeCamera) {
  73677. this._position = this._scene.activeCamera.position.clone();
  73678. }
  73679. if (this._deviceOrientationCamera) {
  73680. this._deviceOrientationCamera.position = this._position;
  73681. this._scene.activeCamera = this._deviceOrientationCamera;
  73682. if (this._canvas) {
  73683. this._scene.activeCamera.attachControl(this._canvas);
  73684. }
  73685. }
  73686. else if (this._existingCamera) {
  73687. this._existingCamera.position = this._position;
  73688. this._scene.activeCamera = this._existingCamera;
  73689. }
  73690. this.updateButtonVisibility();
  73691. if (this._interactionsEnabled) {
  73692. this._scene.unregisterBeforeRender(this.beforeRender);
  73693. }
  73694. };
  73695. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73696. get: function () {
  73697. return this._position;
  73698. },
  73699. set: function (value) {
  73700. this._position = value;
  73701. if (this._scene.activeCamera) {
  73702. this._scene.activeCamera.position = value;
  73703. }
  73704. },
  73705. enumerable: true,
  73706. configurable: true
  73707. });
  73708. VRExperienceHelper.prototype.enableInteractions = function () {
  73709. var _this = this;
  73710. if (!this._interactionsEnabled) {
  73711. this._interactionsRequested = true;
  73712. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73713. this._enableInteractionOnController(this._webVRCamera.leftController);
  73714. }
  73715. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73716. this._enableInteractionOnController(this._webVRCamera.rightController);
  73717. }
  73718. this._createGazeTracker();
  73719. this.raySelectionPredicate = function (mesh) {
  73720. return mesh.isVisible;
  73721. };
  73722. this.meshSelectionPredicate = function (mesh) {
  73723. return true;
  73724. };
  73725. this._raySelectionPredicate = function (mesh) {
  73726. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73727. && mesh.name.indexOf("teleportationTarget") === -1
  73728. && mesh.name.indexOf("torusTeleportation") === -1
  73729. && mesh.name.indexOf("laserPointer") === -1)) {
  73730. return _this.raySelectionPredicate(mesh);
  73731. }
  73732. return false;
  73733. };
  73734. this._interactionsEnabled = true;
  73735. }
  73736. };
  73737. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73738. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73739. if (this._floorMeshesCollection[i].id === mesh.id) {
  73740. return true;
  73741. }
  73742. }
  73743. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73744. return true;
  73745. }
  73746. return false;
  73747. };
  73748. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73749. if (!this._floorMeshesCollection) {
  73750. return;
  73751. }
  73752. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73753. return;
  73754. }
  73755. this._floorMeshesCollection.push(floorMesh);
  73756. };
  73757. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73758. if (!this._floorMeshesCollection) {
  73759. return;
  73760. }
  73761. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73762. if (meshIndex !== -1) {
  73763. this._floorMeshesCollection.splice(meshIndex, 1);
  73764. }
  73765. };
  73766. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73767. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73768. if (!this._teleportationInitialized) {
  73769. this._teleportationRequested = true;
  73770. this.enableInteractions();
  73771. if (vrTeleportationOptions.floorMeshName) {
  73772. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73773. }
  73774. if (vrTeleportationOptions.floorMeshes) {
  73775. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73776. }
  73777. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73778. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73779. }
  73780. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73781. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73782. }
  73783. // Creates an image processing post process for the vignette not relying
  73784. // on the main scene configuration for image processing to reduce setup and spaces
  73785. // (gamma/linear) conflicts.
  73786. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73787. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73788. imageProcessingConfiguration.vignetteEnabled = true;
  73789. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73790. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73791. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73792. this._teleportationInitialized = true;
  73793. if (this._isDefaultTeleportationTarget) {
  73794. this._createTeleportationCircles();
  73795. }
  73796. }
  73797. };
  73798. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73799. var _this = this;
  73800. var controllerMesh = webVRController.mesh;
  73801. if (controllerMesh) {
  73802. var makeNotPick = function (root) {
  73803. root.name += " laserPointer";
  73804. root.getChildMeshes().forEach(function (c) {
  73805. makeNotPick(c);
  73806. });
  73807. };
  73808. makeNotPick(controllerMesh);
  73809. var childMeshes = controllerMesh.getChildMeshes();
  73810. for (var i = 0; i < childMeshes.length; i++) {
  73811. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73812. controllerMesh = childMeshes[i];
  73813. break;
  73814. }
  73815. }
  73816. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73817. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73818. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73819. laserPointerMaterial.alpha = 0.6;
  73820. laserPointer.material = laserPointerMaterial;
  73821. laserPointer.rotation.x = Math.PI / 2;
  73822. laserPointer.parent = controllerMesh;
  73823. laserPointer.position.z = -0.5;
  73824. laserPointer.isVisible = false;
  73825. if (webVRController.hand === "left") {
  73826. this._leftLaserPointer = laserPointer;
  73827. this._interactionsEnabledOnLeftController = true;
  73828. if (!this._rightLaserPointer) {
  73829. this._leftLaserPointer.isVisible = true;
  73830. }
  73831. }
  73832. else {
  73833. this._rightLaserPointer = laserPointer;
  73834. this._interactionsEnabledOnRightController = true;
  73835. if (!this._leftLaserPointer) {
  73836. this._rightLaserPointer.isVisible = true;
  73837. }
  73838. }
  73839. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73840. // Enabling / disabling laserPointer
  73841. if (_this._displayLaserPointer && stateObject.value === 1) {
  73842. laserPointer.isVisible = !laserPointer.isVisible;
  73843. // Laser pointer can only be active on left or right, not both at the same time
  73844. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73845. _this._rightLaserPointer.isVisible = false;
  73846. }
  73847. else if (_this._leftLaserPointer) {
  73848. _this._leftLaserPointer.isVisible = false;
  73849. }
  73850. }
  73851. });
  73852. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73853. if (!_this._pointerDownOnMeshAsked) {
  73854. if (stateObject.value > _this._padSensibilityUp) {
  73855. _this._selectionPointerDown();
  73856. }
  73857. }
  73858. else if (stateObject.value < _this._padSensibilityDown) {
  73859. _this._selectionPointerUp();
  73860. }
  73861. });
  73862. }
  73863. };
  73864. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73865. if (webVRController === void 0) { webVRController = null; }
  73866. if (!this._teleportationRequestInitiated) {
  73867. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73868. if (webVRController) {
  73869. // If laser pointer wasn't enabled yet
  73870. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73871. this._leftLaserPointer.isVisible = true;
  73872. if (this._rightLaserPointer) {
  73873. this._rightLaserPointer.isVisible = false;
  73874. }
  73875. }
  73876. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73877. this._rightLaserPointer.isVisible = true;
  73878. if (this._leftLaserPointer) {
  73879. this._leftLaserPointer.isVisible = false;
  73880. }
  73881. }
  73882. }
  73883. this._teleportationRequestInitiated = true;
  73884. }
  73885. }
  73886. else {
  73887. // Listening to the proper controller values changes to confirm teleportation
  73888. if (webVRController == null
  73889. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73890. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73891. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73892. if (this._teleportationAllowed) {
  73893. this._teleportationAllowed = false;
  73894. this._teleportCamera();
  73895. }
  73896. this._teleportationRequestInitiated = false;
  73897. }
  73898. }
  73899. }
  73900. };
  73901. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73902. this._pointerDownOnMeshAsked = true;
  73903. if (this._currentMeshSelected && this._currentHit) {
  73904. this._scene.simulatePointerDown(this._currentHit);
  73905. }
  73906. };
  73907. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73908. if (this._currentMeshSelected && this._currentHit) {
  73909. this._scene.simulatePointerUp(this._currentHit);
  73910. }
  73911. this._pointerDownOnMeshAsked = false;
  73912. };
  73913. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73914. // Only rotate when user is not currently selecting a teleportation location
  73915. if (this._teleportationRequestInitiated) {
  73916. return;
  73917. }
  73918. if (!this._rotationLeftAsked) {
  73919. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73920. this._rotationLeftAsked = true;
  73921. if (this._rotationAllowed) {
  73922. this._rotateCamera(false);
  73923. }
  73924. }
  73925. }
  73926. else {
  73927. if (stateObject.x > -this._padSensibilityDown) {
  73928. this._rotationLeftAsked = false;
  73929. }
  73930. }
  73931. if (!this._rotationRightAsked) {
  73932. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73933. this._rotationRightAsked = true;
  73934. if (this._rotationAllowed) {
  73935. this._rotateCamera(true);
  73936. }
  73937. }
  73938. }
  73939. else {
  73940. if (stateObject.x < this._padSensibilityDown) {
  73941. this._rotationRightAsked = false;
  73942. }
  73943. }
  73944. };
  73945. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73946. // Only teleport backwards when user is not currently selecting a teleportation location
  73947. if (this._teleportationRequestInitiated) {
  73948. return;
  73949. }
  73950. // Teleport backwards
  73951. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73952. if (!this._teleportationBackRequestInitiated) {
  73953. if (!this.currentVRCamera) {
  73954. return;
  73955. }
  73956. // Get rotation and position of the current camera
  73957. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73958. var position = this.currentVRCamera.position;
  73959. // If the camera has device position, use that instead
  73960. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73961. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73962. position = this.currentVRCamera.devicePosition;
  73963. }
  73964. // Get matrix with only the y rotation of the device rotation
  73965. rotation.toEulerAnglesToRef(this._workingVector);
  73966. this._workingVector.z = 0;
  73967. this._workingVector.x = 0;
  73968. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73969. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73970. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73971. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73972. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73973. var ray = new BABYLON.Ray(position, this._workingVector);
  73974. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73975. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73976. this._teleportCamera(hit.pickedPoint);
  73977. }
  73978. this._teleportationBackRequestInitiated = true;
  73979. }
  73980. }
  73981. else {
  73982. this._teleportationBackRequestInitiated = false;
  73983. }
  73984. };
  73985. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73986. var _this = this;
  73987. var controllerMesh = webVRController.mesh;
  73988. if (controllerMesh) {
  73989. if (webVRController.hand === "left") {
  73990. if (!this._interactionsEnabledOnLeftController) {
  73991. this._enableInteractionOnController(webVRController);
  73992. }
  73993. this._teleportationEnabledOnLeftController = true;
  73994. }
  73995. else {
  73996. if (!this._interactionsEnabledOnRightController) {
  73997. this._enableInteractionOnController(webVRController);
  73998. }
  73999. this._teleportationEnabledOnRightController = true;
  74000. }
  74001. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74002. this._dpadPressed = false;
  74003. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74004. _this._dpadPressed = stateObject.pressed;
  74005. if (!_this._dpadPressed) {
  74006. _this._rotationLeftAsked = false;
  74007. _this._rotationRightAsked = false;
  74008. _this._teleportationBackRequestInitiated = false;
  74009. }
  74010. });
  74011. }
  74012. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74013. if (_this.teleportationEnabled) {
  74014. _this._checkTeleportBackwards(stateObject);
  74015. _this._checkTeleportWithRay(stateObject, webVRController);
  74016. }
  74017. _this._checkRotate(stateObject);
  74018. });
  74019. }
  74020. };
  74021. // Gaze support used to point to teleport or to interact with an object
  74022. VRExperienceHelper.prototype._createGazeTracker = function () {
  74023. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74024. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74025. this._gazeTracker.isPickable = false;
  74026. this._gazeTracker.isVisible = false;
  74027. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74028. targetMat.specularColor = BABYLON.Color3.Black();
  74029. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74030. targetMat.backFaceCulling = false;
  74031. this._gazeTracker.material = targetMat;
  74032. };
  74033. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74034. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74035. this._teleportationTarget.isPickable = false;
  74036. var length = 512;
  74037. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74038. dynamicTexture.hasAlpha = true;
  74039. var context = dynamicTexture.getContext();
  74040. var centerX = length / 2;
  74041. var centerY = length / 2;
  74042. var radius = 200;
  74043. context.beginPath();
  74044. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74045. context.fillStyle = this._teleportationFillColor;
  74046. context.fill();
  74047. context.lineWidth = 10;
  74048. context.strokeStyle = this._teleportationBorderColor;
  74049. context.stroke();
  74050. context.closePath();
  74051. dynamicTexture.update();
  74052. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74053. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74054. this._teleportationTarget.material = teleportationCircleMaterial;
  74055. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74056. torus.isPickable = false;
  74057. torus.parent = this._teleportationTarget;
  74058. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74059. var keys = [];
  74060. keys.push({
  74061. frame: 0,
  74062. value: 0
  74063. });
  74064. keys.push({
  74065. frame: 30,
  74066. value: 0.4
  74067. });
  74068. keys.push({
  74069. frame: 60,
  74070. value: 0
  74071. });
  74072. animationInnerCircle.setKeys(keys);
  74073. var easingFunction = new BABYLON.SineEase();
  74074. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74075. animationInnerCircle.setEasingFunction(easingFunction);
  74076. torus.animations = [];
  74077. torus.animations.push(animationInnerCircle);
  74078. this._scene.beginAnimation(torus, 0, 60, true);
  74079. this._hideTeleportationTarget();
  74080. };
  74081. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74082. if (this._teleportationInitialized) {
  74083. this._teleportationTarget.isVisible = true;
  74084. if (this._isDefaultTeleportationTarget) {
  74085. this._teleportationTarget.getChildren()[0].isVisible = true;
  74086. }
  74087. }
  74088. };
  74089. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74090. if (this._teleportationInitialized) {
  74091. this._teleportationTarget.isVisible = false;
  74092. if (this._isDefaultTeleportationTarget) {
  74093. this._teleportationTarget.getChildren()[0].isVisible = false;
  74094. }
  74095. }
  74096. };
  74097. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74098. var _this = this;
  74099. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74100. return;
  74101. }
  74102. if (right) {
  74103. this._rotationAngle++;
  74104. }
  74105. else {
  74106. this._rotationAngle--;
  74107. }
  74108. this.currentVRCamera.animations = [];
  74109. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74110. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74111. var animationRotationKeys = [];
  74112. animationRotationKeys.push({
  74113. frame: 0,
  74114. value: this.currentVRCamera.rotationQuaternion
  74115. });
  74116. animationRotationKeys.push({
  74117. frame: 6,
  74118. value: target
  74119. });
  74120. animationRotation.setKeys(animationRotationKeys);
  74121. animationRotation.setEasingFunction(this._circleEase);
  74122. this.currentVRCamera.animations.push(animationRotation);
  74123. this._postProcessMove.animations = [];
  74124. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74125. var vignetteWeightKeys = [];
  74126. vignetteWeightKeys.push({
  74127. frame: 0,
  74128. value: 0
  74129. });
  74130. vignetteWeightKeys.push({
  74131. frame: 3,
  74132. value: 4
  74133. });
  74134. vignetteWeightKeys.push({
  74135. frame: 6,
  74136. value: 0
  74137. });
  74138. animationPP.setKeys(vignetteWeightKeys);
  74139. animationPP.setEasingFunction(this._circleEase);
  74140. this._postProcessMove.animations.push(animationPP);
  74141. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74142. var vignetteStretchKeys = [];
  74143. vignetteStretchKeys.push({
  74144. frame: 0,
  74145. value: 0
  74146. });
  74147. vignetteStretchKeys.push({
  74148. frame: 3,
  74149. value: 10
  74150. });
  74151. vignetteStretchKeys.push({
  74152. frame: 6,
  74153. value: 0
  74154. });
  74155. animationPP2.setKeys(vignetteStretchKeys);
  74156. animationPP2.setEasingFunction(this._circleEase);
  74157. this._postProcessMove.animations.push(animationPP2);
  74158. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74159. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74160. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74161. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74162. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74163. });
  74164. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74165. };
  74166. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74167. if (hit.pickedPoint) {
  74168. this._teleportationAllowed = true;
  74169. if (this._teleportationRequestInitiated) {
  74170. this._displayTeleportationTarget();
  74171. }
  74172. else {
  74173. this._hideTeleportationTarget();
  74174. }
  74175. this._haloCenter.copyFrom(hit.pickedPoint);
  74176. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74177. var pickNormal = hit.getNormal(true, false);
  74178. if (pickNormal) {
  74179. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74180. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74181. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74182. }
  74183. this._teleportationTarget.position.y += 0.1;
  74184. }
  74185. };
  74186. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74187. var _this = this;
  74188. if (location === void 0) { location = null; }
  74189. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74190. return;
  74191. }
  74192. if (!location) {
  74193. location = this._haloCenter;
  74194. }
  74195. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74196. // offset of the headset from the anchor.
  74197. if (this.webVRCamera.leftCamera) {
  74198. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74199. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74200. location.subtractToRef(this._workingVector, this._workingVector);
  74201. }
  74202. else {
  74203. this._workingVector.copyFrom(location);
  74204. }
  74205. // Add height to account for user's height offset
  74206. if (this.isInVRMode) {
  74207. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74208. }
  74209. else {
  74210. this._workingVector.y += this._defaultHeight;
  74211. }
  74212. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74213. // Create animation from the camera's position to the new location
  74214. this.currentVRCamera.animations = [];
  74215. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74216. var animationCameraTeleportationKeys = [{
  74217. frame: 0,
  74218. value: this.currentVRCamera.position
  74219. },
  74220. {
  74221. frame: 11,
  74222. value: this._workingVector
  74223. }
  74224. ];
  74225. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74226. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74227. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74228. this._postProcessMove.animations = [];
  74229. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74230. var vignetteWeightKeys = [];
  74231. vignetteWeightKeys.push({
  74232. frame: 0,
  74233. value: 0
  74234. });
  74235. vignetteWeightKeys.push({
  74236. frame: 5,
  74237. value: 8
  74238. });
  74239. vignetteWeightKeys.push({
  74240. frame: 11,
  74241. value: 0
  74242. });
  74243. animationPP.setKeys(vignetteWeightKeys);
  74244. this._postProcessMove.animations.push(animationPP);
  74245. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74246. var vignetteStretchKeys = [];
  74247. vignetteStretchKeys.push({
  74248. frame: 0,
  74249. value: 0
  74250. });
  74251. vignetteStretchKeys.push({
  74252. frame: 5,
  74253. value: 10
  74254. });
  74255. vignetteStretchKeys.push({
  74256. frame: 11,
  74257. value: 0
  74258. });
  74259. animationPP2.setKeys(vignetteStretchKeys);
  74260. this._postProcessMove.animations.push(animationPP2);
  74261. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74262. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74263. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74264. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74265. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74266. });
  74267. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74268. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74269. });
  74270. };
  74271. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74272. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74273. return;
  74274. }
  74275. var ray;
  74276. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74277. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74278. }
  74279. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74280. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74281. }
  74282. else {
  74283. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74284. }
  74285. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74286. // Moving the gazeTracker on the mesh face targetted
  74287. if (hit && hit.pickedPoint) {
  74288. if (this._displayGaze) {
  74289. var multiplier = 1;
  74290. this._gazeTracker.isVisible = true;
  74291. if (this._isActionableMesh) {
  74292. multiplier = 3;
  74293. }
  74294. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74295. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74296. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74297. var pickNormal = hit.getNormal();
  74298. // To avoid z-fighting
  74299. var deltaFighting = 0.002;
  74300. if (pickNormal) {
  74301. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74302. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74303. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74304. }
  74305. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74306. if (this._gazeTracker.position.x < 0) {
  74307. this._gazeTracker.position.x += deltaFighting;
  74308. }
  74309. else {
  74310. this._gazeTracker.position.x -= deltaFighting;
  74311. }
  74312. if (this._gazeTracker.position.y < 0) {
  74313. this._gazeTracker.position.y += deltaFighting;
  74314. }
  74315. else {
  74316. this._gazeTracker.position.y -= deltaFighting;
  74317. }
  74318. if (this._gazeTracker.position.z < 0) {
  74319. this._gazeTracker.position.z += deltaFighting;
  74320. }
  74321. else {
  74322. this._gazeTracker.position.z -= deltaFighting;
  74323. }
  74324. }
  74325. // Changing the size of the laser pointer based on the distance from the targetted point
  74326. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74327. this._rightLaserPointer.scaling.y = hit.distance;
  74328. this._rightLaserPointer.position.z = -hit.distance / 2;
  74329. }
  74330. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74331. this._leftLaserPointer.scaling.y = hit.distance;
  74332. this._leftLaserPointer.position.z = -hit.distance / 2;
  74333. }
  74334. }
  74335. else {
  74336. this._gazeTracker.isVisible = false;
  74337. }
  74338. if (hit && hit.pickedMesh) {
  74339. this._currentHit = hit;
  74340. if (this._pointerDownOnMeshAsked) {
  74341. this._scene.simulatePointerMove(this._currentHit);
  74342. }
  74343. // The object selected is the floor, we're in a teleportation scenario
  74344. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74345. // Moving the teleportation area to this targetted point
  74346. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74347. if (this._currentMeshSelected &&
  74348. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74349. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74350. }
  74351. this._currentMeshSelected = null;
  74352. this._moveTeleportationSelectorTo(hit);
  74353. return;
  74354. }
  74355. // If not, we're in a selection scenario
  74356. this._hideTeleportationTarget();
  74357. this._teleportationAllowed = false;
  74358. if (hit.pickedMesh !== this._currentMeshSelected) {
  74359. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74360. this.onNewMeshPicked.notifyObservers(hit);
  74361. this._currentMeshSelected = hit.pickedMesh;
  74362. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74363. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74364. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74365. this._isActionableMesh = true;
  74366. }
  74367. else {
  74368. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74369. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74370. this._isActionableMesh = false;
  74371. }
  74372. try {
  74373. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74374. }
  74375. catch (err) {
  74376. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74377. }
  74378. }
  74379. else {
  74380. if (this._currentMeshSelected) {
  74381. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74382. }
  74383. this._currentMeshSelected = null;
  74384. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74385. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74386. }
  74387. }
  74388. }
  74389. else {
  74390. this._currentHit = null;
  74391. this._currentMeshSelected = null;
  74392. this._teleportationAllowed = false;
  74393. this._hideTeleportationTarget();
  74394. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74395. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74396. }
  74397. };
  74398. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74399. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74400. this._leftLaserPointer.material.emissiveColor = color;
  74401. }
  74402. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74403. this._rightLaserPointer.material.emissiveColor = color;
  74404. }
  74405. };
  74406. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74407. if (this._gazeTracker.material) {
  74408. this._gazeTracker.material.emissiveColor = color;
  74409. }
  74410. };
  74411. VRExperienceHelper.prototype.dispose = function () {
  74412. if (this.isInVRMode) {
  74413. this.exitVR();
  74414. }
  74415. if (this._passProcessMove) {
  74416. this._passProcessMove.dispose();
  74417. }
  74418. if (this._postProcessMove) {
  74419. this._postProcessMove.dispose();
  74420. }
  74421. if (this._webVRCamera) {
  74422. this._webVRCamera.dispose();
  74423. }
  74424. if (this._vrDeviceOrientationCamera) {
  74425. this._vrDeviceOrientationCamera.dispose();
  74426. }
  74427. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74428. document.body.removeChild(this._btnVR);
  74429. }
  74430. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74431. this._deviceOrientationCamera.dispose();
  74432. }
  74433. if (this._gazeTracker) {
  74434. this._gazeTracker.dispose();
  74435. }
  74436. if (this._teleportationTarget) {
  74437. this._teleportationTarget.dispose();
  74438. }
  74439. this._floorMeshesCollection = [];
  74440. document.removeEventListener("keydown", this._onKeyDown);
  74441. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74442. window.removeEventListener("resize", this._onResize);
  74443. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74444. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74445. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74446. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74447. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74448. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74449. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74450. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74451. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74452. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74453. this._scene.unregisterBeforeRender(this.beforeRender);
  74454. };
  74455. VRExperienceHelper.prototype.getClassName = function () {
  74456. return "VRExperienceHelper";
  74457. };
  74458. return VRExperienceHelper;
  74459. }());
  74460. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74461. })(BABYLON || (BABYLON = {}));
  74462. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74463. // Mainly based on these 2 articles :
  74464. // 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
  74465. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74466. var BABYLON;
  74467. (function (BABYLON) {
  74468. var JoystickAxis;
  74469. (function (JoystickAxis) {
  74470. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74471. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74472. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74473. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74474. var VirtualJoystick = /** @class */ (function () {
  74475. function VirtualJoystick(leftJoystick) {
  74476. var _this = this;
  74477. if (leftJoystick) {
  74478. this._leftJoystick = true;
  74479. }
  74480. else {
  74481. this._leftJoystick = false;
  74482. }
  74483. VirtualJoystick._globalJoystickIndex++;
  74484. // By default left & right arrow keys are moving the X
  74485. // and up & down keys are moving the Y
  74486. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74487. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74488. this.reverseLeftRight = false;
  74489. this.reverseUpDown = false;
  74490. // collections of pointers
  74491. this._touches = new BABYLON.StringDictionary();
  74492. this.deltaPosition = BABYLON.Vector3.Zero();
  74493. this._joystickSensibility = 25;
  74494. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74495. this._onResize = function (evt) {
  74496. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74497. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74498. if (VirtualJoystick.vjCanvas) {
  74499. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74500. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74501. }
  74502. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74503. };
  74504. // injecting a canvas element on top of the canvas 3D game
  74505. if (!VirtualJoystick.vjCanvas) {
  74506. window.addEventListener("resize", this._onResize, false);
  74507. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74508. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74509. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74510. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74511. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74512. VirtualJoystick.vjCanvas.style.width = "100%";
  74513. VirtualJoystick.vjCanvas.style.height = "100%";
  74514. VirtualJoystick.vjCanvas.style.position = "absolute";
  74515. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74516. VirtualJoystick.vjCanvas.style.top = "0px";
  74517. VirtualJoystick.vjCanvas.style.left = "0px";
  74518. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74519. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74520. // Support for jQuery PEP polyfill
  74521. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74522. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74523. if (!context) {
  74524. throw new Error("Unable to create canvas for virtual joystick");
  74525. }
  74526. VirtualJoystick.vjCanvasContext = context;
  74527. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74528. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74529. document.body.appendChild(VirtualJoystick.vjCanvas);
  74530. }
  74531. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74532. this.pressed = false;
  74533. // default joystick color
  74534. this._joystickColor = "cyan";
  74535. this._joystickPointerID = -1;
  74536. // current joystick position
  74537. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74538. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74539. // origin joystick position
  74540. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74541. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74542. this._onPointerDownHandlerRef = function (evt) {
  74543. _this._onPointerDown(evt);
  74544. };
  74545. this._onPointerMoveHandlerRef = function (evt) {
  74546. _this._onPointerMove(evt);
  74547. };
  74548. this._onPointerUpHandlerRef = function (evt) {
  74549. _this._onPointerUp(evt);
  74550. };
  74551. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74552. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74553. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74554. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74555. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74556. evt.preventDefault(); // Disables system menu
  74557. }, false);
  74558. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74559. }
  74560. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74561. this._joystickSensibility = newJoystickSensibility;
  74562. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74563. };
  74564. VirtualJoystick.prototype._onPointerDown = function (e) {
  74565. var positionOnScreenCondition;
  74566. e.preventDefault();
  74567. if (this._leftJoystick === true) {
  74568. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74569. }
  74570. else {
  74571. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74572. }
  74573. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74574. // First contact will be dedicated to the virtual joystick
  74575. this._joystickPointerID = e.pointerId;
  74576. this._joystickPointerStartPos.x = e.clientX;
  74577. this._joystickPointerStartPos.y = e.clientY;
  74578. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74579. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74580. this._deltaJoystickVector.x = 0;
  74581. this._deltaJoystickVector.y = 0;
  74582. this.pressed = true;
  74583. this._touches.add(e.pointerId.toString(), e);
  74584. }
  74585. else {
  74586. // You can only trigger the action buttons with a joystick declared
  74587. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74588. this._action();
  74589. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74590. }
  74591. }
  74592. };
  74593. VirtualJoystick.prototype._onPointerMove = function (e) {
  74594. // If the current pointer is the one associated to the joystick (first touch contact)
  74595. if (this._joystickPointerID == e.pointerId) {
  74596. this._joystickPointerPos.x = e.clientX;
  74597. this._joystickPointerPos.y = e.clientY;
  74598. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74599. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74600. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74601. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74602. switch (this._axisTargetedByLeftAndRight) {
  74603. case JoystickAxis.X:
  74604. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74605. break;
  74606. case JoystickAxis.Y:
  74607. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74608. break;
  74609. case JoystickAxis.Z:
  74610. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74611. break;
  74612. }
  74613. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74614. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74615. switch (this._axisTargetedByUpAndDown) {
  74616. case JoystickAxis.X:
  74617. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74618. break;
  74619. case JoystickAxis.Y:
  74620. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74621. break;
  74622. case JoystickAxis.Z:
  74623. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74624. break;
  74625. }
  74626. }
  74627. else {
  74628. var data = this._touches.get(e.pointerId.toString());
  74629. if (data) {
  74630. data.x = e.clientX;
  74631. data.y = e.clientY;
  74632. }
  74633. }
  74634. };
  74635. VirtualJoystick.prototype._onPointerUp = function (e) {
  74636. if (this._joystickPointerID == e.pointerId) {
  74637. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74638. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74639. this._joystickPointerID = -1;
  74640. this.pressed = false;
  74641. }
  74642. else {
  74643. var touch = this._touches.get(e.pointerId.toString());
  74644. if (touch) {
  74645. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74646. }
  74647. }
  74648. this._deltaJoystickVector.x = 0;
  74649. this._deltaJoystickVector.y = 0;
  74650. this._touches.remove(e.pointerId.toString());
  74651. };
  74652. /**
  74653. * Change the color of the virtual joystick
  74654. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74655. */
  74656. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74657. this._joystickColor = newColor;
  74658. };
  74659. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74660. this._action = action;
  74661. };
  74662. // Define which axis you'd like to control for left & right
  74663. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74664. switch (axis) {
  74665. case JoystickAxis.X:
  74666. case JoystickAxis.Y:
  74667. case JoystickAxis.Z:
  74668. this._axisTargetedByLeftAndRight = axis;
  74669. break;
  74670. default:
  74671. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74672. break;
  74673. }
  74674. };
  74675. // Define which axis you'd like to control for up & down
  74676. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74677. switch (axis) {
  74678. case JoystickAxis.X:
  74679. case JoystickAxis.Y:
  74680. case JoystickAxis.Z:
  74681. this._axisTargetedByUpAndDown = axis;
  74682. break;
  74683. default:
  74684. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74685. break;
  74686. }
  74687. };
  74688. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74689. var _this = this;
  74690. if (this.pressed) {
  74691. this._touches.forEach(function (key, touch) {
  74692. if (touch.pointerId === _this._joystickPointerID) {
  74693. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74694. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74695. VirtualJoystick.vjCanvasContext.beginPath();
  74696. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74697. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74698. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74699. VirtualJoystick.vjCanvasContext.stroke();
  74700. VirtualJoystick.vjCanvasContext.closePath();
  74701. VirtualJoystick.vjCanvasContext.beginPath();
  74702. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74703. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74704. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74705. VirtualJoystick.vjCanvasContext.stroke();
  74706. VirtualJoystick.vjCanvasContext.closePath();
  74707. VirtualJoystick.vjCanvasContext.beginPath();
  74708. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74709. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74710. VirtualJoystick.vjCanvasContext.stroke();
  74711. VirtualJoystick.vjCanvasContext.closePath();
  74712. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74713. }
  74714. else {
  74715. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74716. VirtualJoystick.vjCanvasContext.beginPath();
  74717. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74718. VirtualJoystick.vjCanvasContext.beginPath();
  74719. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74720. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74721. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74722. VirtualJoystick.vjCanvasContext.stroke();
  74723. VirtualJoystick.vjCanvasContext.closePath();
  74724. touch.prevX = touch.x;
  74725. touch.prevY = touch.y;
  74726. }
  74727. ;
  74728. });
  74729. }
  74730. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74731. };
  74732. VirtualJoystick.prototype.releaseCanvas = function () {
  74733. if (VirtualJoystick.vjCanvas) {
  74734. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74735. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74736. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74737. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74738. window.removeEventListener("resize", this._onResize);
  74739. document.body.removeChild(VirtualJoystick.vjCanvas);
  74740. VirtualJoystick.vjCanvas = null;
  74741. }
  74742. };
  74743. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74744. VirtualJoystick._globalJoystickIndex = 0;
  74745. return VirtualJoystick;
  74746. }());
  74747. BABYLON.VirtualJoystick = VirtualJoystick;
  74748. })(BABYLON || (BABYLON = {}));
  74749. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74750. var BABYLON;
  74751. (function (BABYLON) {
  74752. // We're mainly based on the logic defined into the FreeCamera code
  74753. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74754. __extends(VirtualJoysticksCamera, _super);
  74755. function VirtualJoysticksCamera(name, position, scene) {
  74756. var _this = _super.call(this, name, position, scene) || this;
  74757. _this.inputs.addVirtualJoystick();
  74758. return _this;
  74759. }
  74760. VirtualJoysticksCamera.prototype.getClassName = function () {
  74761. return "VirtualJoysticksCamera";
  74762. };
  74763. return VirtualJoysticksCamera;
  74764. }(BABYLON.FreeCamera));
  74765. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74766. })(BABYLON || (BABYLON = {}));
  74767. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74768. var BABYLON;
  74769. (function (BABYLON) {
  74770. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74771. function FreeCameraVirtualJoystickInput() {
  74772. }
  74773. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74774. return this._leftjoystick;
  74775. };
  74776. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74777. return this._rightjoystick;
  74778. };
  74779. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74780. if (this._leftjoystick) {
  74781. var camera = this.camera;
  74782. var speed = camera._computeLocalCameraSpeed() * 50;
  74783. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74784. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74785. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74786. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74787. if (!this._leftjoystick.pressed) {
  74788. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74789. }
  74790. if (!this._rightjoystick.pressed) {
  74791. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74792. }
  74793. }
  74794. };
  74795. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74796. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74797. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74798. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74799. this._leftjoystick.setJoystickSensibility(0.15);
  74800. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74801. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74802. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74803. this._rightjoystick.reverseUpDown = true;
  74804. this._rightjoystick.setJoystickSensibility(0.05);
  74805. this._rightjoystick.setJoystickColor("yellow");
  74806. };
  74807. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74808. this._leftjoystick.releaseCanvas();
  74809. this._rightjoystick.releaseCanvas();
  74810. };
  74811. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74812. return "FreeCameraVirtualJoystickInput";
  74813. };
  74814. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74815. return "virtualJoystick";
  74816. };
  74817. return FreeCameraVirtualJoystickInput;
  74818. }());
  74819. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74820. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74821. })(BABYLON || (BABYLON = {}));
  74822. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74823. var BABYLON;
  74824. (function (BABYLON) {
  74825. var SimplificationSettings = /** @class */ (function () {
  74826. function SimplificationSettings(quality, distance, optimizeMesh) {
  74827. this.quality = quality;
  74828. this.distance = distance;
  74829. this.optimizeMesh = optimizeMesh;
  74830. }
  74831. return SimplificationSettings;
  74832. }());
  74833. BABYLON.SimplificationSettings = SimplificationSettings;
  74834. var SimplificationQueue = /** @class */ (function () {
  74835. function SimplificationQueue() {
  74836. this.running = false;
  74837. this._simplificationArray = [];
  74838. }
  74839. SimplificationQueue.prototype.addTask = function (task) {
  74840. this._simplificationArray.push(task);
  74841. };
  74842. SimplificationQueue.prototype.executeNext = function () {
  74843. var task = this._simplificationArray.pop();
  74844. if (task) {
  74845. this.running = true;
  74846. this.runSimplification(task);
  74847. }
  74848. else {
  74849. this.running = false;
  74850. }
  74851. };
  74852. SimplificationQueue.prototype.runSimplification = function (task) {
  74853. var _this = this;
  74854. if (task.parallelProcessing) {
  74855. //parallel simplifier
  74856. task.settings.forEach(function (setting) {
  74857. var simplifier = _this.getSimplifier(task);
  74858. simplifier.simplify(setting, function (newMesh) {
  74859. task.mesh.addLODLevel(setting.distance, newMesh);
  74860. newMesh.isVisible = true;
  74861. //check if it is the last
  74862. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74863. //all done, run the success callback.
  74864. task.successCallback();
  74865. }
  74866. _this.executeNext();
  74867. });
  74868. });
  74869. }
  74870. else {
  74871. //single simplifier.
  74872. var simplifier = this.getSimplifier(task);
  74873. var runDecimation = function (setting, callback) {
  74874. simplifier.simplify(setting, function (newMesh) {
  74875. task.mesh.addLODLevel(setting.distance, newMesh);
  74876. newMesh.isVisible = true;
  74877. //run the next quality level
  74878. callback();
  74879. });
  74880. };
  74881. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74882. runDecimation(task.settings[loop.index], function () {
  74883. loop.executeNext();
  74884. });
  74885. }, function () {
  74886. //execution ended, run the success callback.
  74887. if (task.successCallback) {
  74888. task.successCallback();
  74889. }
  74890. _this.executeNext();
  74891. });
  74892. }
  74893. };
  74894. SimplificationQueue.prototype.getSimplifier = function (task) {
  74895. switch (task.simplificationType) {
  74896. case SimplificationType.QUADRATIC:
  74897. default:
  74898. return new QuadraticErrorSimplification(task.mesh);
  74899. }
  74900. };
  74901. return SimplificationQueue;
  74902. }());
  74903. BABYLON.SimplificationQueue = SimplificationQueue;
  74904. /**
  74905. * The implemented types of simplification.
  74906. * At the moment only Quadratic Error Decimation is implemented.
  74907. */
  74908. var SimplificationType;
  74909. (function (SimplificationType) {
  74910. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74911. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74912. var DecimationTriangle = /** @class */ (function () {
  74913. function DecimationTriangle(vertices) {
  74914. this.vertices = vertices;
  74915. this.error = new Array(4);
  74916. this.deleted = false;
  74917. this.isDirty = false;
  74918. this.deletePending = false;
  74919. this.borderFactor = 0;
  74920. }
  74921. return DecimationTriangle;
  74922. }());
  74923. BABYLON.DecimationTriangle = DecimationTriangle;
  74924. var DecimationVertex = /** @class */ (function () {
  74925. function DecimationVertex(position, id) {
  74926. this.position = position;
  74927. this.id = id;
  74928. this.isBorder = true;
  74929. this.q = new QuadraticMatrix();
  74930. this.triangleCount = 0;
  74931. this.triangleStart = 0;
  74932. this.originalOffsets = [];
  74933. }
  74934. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74935. this.position.copyFrom(newPosition);
  74936. };
  74937. return DecimationVertex;
  74938. }());
  74939. BABYLON.DecimationVertex = DecimationVertex;
  74940. var QuadraticMatrix = /** @class */ (function () {
  74941. function QuadraticMatrix(data) {
  74942. this.data = new Array(10);
  74943. for (var i = 0; i < 10; ++i) {
  74944. if (data && data[i]) {
  74945. this.data[i] = data[i];
  74946. }
  74947. else {
  74948. this.data[i] = 0;
  74949. }
  74950. }
  74951. }
  74952. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74953. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74954. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74955. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74956. return det;
  74957. };
  74958. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74959. for (var i = 0; i < 10; ++i) {
  74960. this.data[i] += matrix.data[i];
  74961. }
  74962. };
  74963. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74964. for (var i = 0; i < 10; ++i) {
  74965. this.data[i] += data[i];
  74966. }
  74967. };
  74968. QuadraticMatrix.prototype.add = function (matrix) {
  74969. var m = new QuadraticMatrix();
  74970. for (var i = 0; i < 10; ++i) {
  74971. m.data[i] = this.data[i] + matrix.data[i];
  74972. }
  74973. return m;
  74974. };
  74975. QuadraticMatrix.FromData = function (a, b, c, d) {
  74976. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74977. };
  74978. //returning an array to avoid garbage collection
  74979. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74980. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74981. };
  74982. return QuadraticMatrix;
  74983. }());
  74984. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74985. var Reference = /** @class */ (function () {
  74986. function Reference(vertexId, triangleId) {
  74987. this.vertexId = vertexId;
  74988. this.triangleId = triangleId;
  74989. }
  74990. return Reference;
  74991. }());
  74992. BABYLON.Reference = Reference;
  74993. /**
  74994. * An implementation of the Quadratic Error simplification algorithm.
  74995. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74996. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74997. * @author RaananW
  74998. */
  74999. var QuadraticErrorSimplification = /** @class */ (function () {
  75000. function QuadraticErrorSimplification(_mesh) {
  75001. this._mesh = _mesh;
  75002. this.syncIterations = 5000;
  75003. this.aggressiveness = 7;
  75004. this.decimationIterations = 100;
  75005. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75006. }
  75007. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75008. var _this = this;
  75009. this.initDecimatedMesh();
  75010. //iterating through the submeshes array, one after the other.
  75011. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75012. _this.initWithMesh(loop.index, function () {
  75013. _this.runDecimation(settings, loop.index, function () {
  75014. loop.executeNext();
  75015. });
  75016. }, settings.optimizeMesh);
  75017. }, function () {
  75018. setTimeout(function () {
  75019. successCallback(_this._reconstructedMesh);
  75020. }, 0);
  75021. });
  75022. };
  75023. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75024. var _this = this;
  75025. var targetCount = ~~(this.triangles.length * settings.quality);
  75026. var deletedTriangles = 0;
  75027. var triangleCount = this.triangles.length;
  75028. var iterationFunction = function (iteration, callback) {
  75029. setTimeout(function () {
  75030. if (iteration % 5 === 0) {
  75031. _this.updateMesh(iteration === 0);
  75032. }
  75033. for (var i = 0; i < _this.triangles.length; ++i) {
  75034. _this.triangles[i].isDirty = false;
  75035. }
  75036. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75037. var trianglesIterator = function (i) {
  75038. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75039. var t = _this.triangles[tIdx];
  75040. if (!t)
  75041. return;
  75042. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75043. return;
  75044. }
  75045. for (var j = 0; j < 3; ++j) {
  75046. if (t.error[j] < threshold) {
  75047. var deleted0 = [];
  75048. var deleted1 = [];
  75049. var v0 = t.vertices[j];
  75050. var v1 = t.vertices[(j + 1) % 3];
  75051. if (v0.isBorder || v1.isBorder)
  75052. continue;
  75053. var p = BABYLON.Vector3.Zero();
  75054. var n = BABYLON.Vector3.Zero();
  75055. var uv = BABYLON.Vector2.Zero();
  75056. var color = new BABYLON.Color4(0, 0, 0, 1);
  75057. _this.calculateError(v0, v1, p, n, uv, color);
  75058. var delTr = new Array();
  75059. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75060. continue;
  75061. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75062. continue;
  75063. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75064. continue;
  75065. var uniqueArray = new Array();
  75066. delTr.forEach(function (deletedT) {
  75067. if (uniqueArray.indexOf(deletedT) === -1) {
  75068. deletedT.deletePending = true;
  75069. uniqueArray.push(deletedT);
  75070. }
  75071. });
  75072. if (uniqueArray.length % 2 !== 0) {
  75073. continue;
  75074. }
  75075. v0.q = v1.q.add(v0.q);
  75076. v0.updatePosition(p);
  75077. var tStart = _this.references.length;
  75078. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75079. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75080. var tCount = _this.references.length - tStart;
  75081. if (tCount <= v0.triangleCount) {
  75082. if (tCount) {
  75083. for (var c = 0; c < tCount; c++) {
  75084. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75085. }
  75086. }
  75087. }
  75088. else {
  75089. v0.triangleStart = tStart;
  75090. }
  75091. v0.triangleCount = tCount;
  75092. break;
  75093. }
  75094. }
  75095. };
  75096. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75097. }, 0);
  75098. };
  75099. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75100. if (triangleCount - deletedTriangles <= targetCount)
  75101. loop.breakLoop();
  75102. else {
  75103. iterationFunction(loop.index, function () {
  75104. loop.executeNext();
  75105. });
  75106. }
  75107. }, function () {
  75108. setTimeout(function () {
  75109. //reconstruct this part of the mesh
  75110. _this.reconstructMesh(submeshIndex);
  75111. successCallback();
  75112. }, 0);
  75113. });
  75114. };
  75115. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75116. var _this = this;
  75117. this.vertices = [];
  75118. this.triangles = [];
  75119. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75120. var indices = this._mesh.getIndices();
  75121. var submesh = this._mesh.subMeshes[submeshIndex];
  75122. var findInVertices = function (positionToSearch) {
  75123. if (optimizeMesh) {
  75124. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75125. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75126. return _this.vertices[ii];
  75127. }
  75128. }
  75129. }
  75130. return null;
  75131. };
  75132. var vertexReferences = [];
  75133. var vertexInit = function (i) {
  75134. if (!positionData) {
  75135. return;
  75136. }
  75137. var offset = i + submesh.verticesStart;
  75138. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75139. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75140. vertex.originalOffsets.push(offset);
  75141. if (vertex.id === _this.vertices.length) {
  75142. _this.vertices.push(vertex);
  75143. }
  75144. vertexReferences.push(vertex.id);
  75145. };
  75146. //var totalVertices = mesh.getTotalVertices();
  75147. var totalVertices = submesh.verticesCount;
  75148. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75149. var indicesInit = function (i) {
  75150. if (!indices) {
  75151. return;
  75152. }
  75153. var offset = (submesh.indexStart / 3) + i;
  75154. var pos = (offset * 3);
  75155. var i0 = indices[pos + 0];
  75156. var i1 = indices[pos + 1];
  75157. var i2 = indices[pos + 2];
  75158. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75159. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75160. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75161. var triangle = new DecimationTriangle([v0, v1, v2]);
  75162. triangle.originalOffset = pos;
  75163. _this.triangles.push(triangle);
  75164. };
  75165. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75166. _this.init(callback);
  75167. });
  75168. });
  75169. };
  75170. QuadraticErrorSimplification.prototype.init = function (callback) {
  75171. var _this = this;
  75172. var triangleInit1 = function (i) {
  75173. var t = _this.triangles[i];
  75174. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75175. for (var j = 0; j < 3; j++) {
  75176. 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))));
  75177. }
  75178. };
  75179. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75180. var triangleInit2 = function (i) {
  75181. var t = _this.triangles[i];
  75182. for (var j = 0; j < 3; ++j) {
  75183. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75184. }
  75185. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75186. };
  75187. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75188. callback();
  75189. });
  75190. });
  75191. };
  75192. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75193. var newTriangles = [];
  75194. var i;
  75195. for (i = 0; i < this.vertices.length; ++i) {
  75196. this.vertices[i].triangleCount = 0;
  75197. }
  75198. var t;
  75199. var j;
  75200. for (i = 0; i < this.triangles.length; ++i) {
  75201. if (!this.triangles[i].deleted) {
  75202. t = this.triangles[i];
  75203. for (j = 0; j < 3; ++j) {
  75204. t.vertices[j].triangleCount = 1;
  75205. }
  75206. newTriangles.push(t);
  75207. }
  75208. }
  75209. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75210. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75211. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75212. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75213. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75214. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75215. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75216. var vertexCount = 0;
  75217. for (i = 0; i < this.vertices.length; ++i) {
  75218. var vertex = this.vertices[i];
  75219. vertex.id = vertexCount;
  75220. if (vertex.triangleCount) {
  75221. vertex.originalOffsets.forEach(function (originalOffset) {
  75222. if (!normalData) {
  75223. return;
  75224. }
  75225. newPositionData.push(vertex.position.x);
  75226. newPositionData.push(vertex.position.y);
  75227. newPositionData.push(vertex.position.z);
  75228. newNormalData.push(normalData[originalOffset * 3]);
  75229. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75230. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75231. if (uvs && uvs.length) {
  75232. newUVsData.push(uvs[(originalOffset * 2)]);
  75233. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75234. }
  75235. else if (colorsData && colorsData.length) {
  75236. newColorsData.push(colorsData[(originalOffset * 4)]);
  75237. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75238. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75239. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75240. }
  75241. ++vertexCount;
  75242. });
  75243. }
  75244. }
  75245. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75246. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75247. var submeshesArray = this._reconstructedMesh.subMeshes;
  75248. this._reconstructedMesh.subMeshes = [];
  75249. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75250. var originalIndices = this._mesh.getIndices();
  75251. for (i = 0; i < newTriangles.length; ++i) {
  75252. t = newTriangles[i]; //now get the new referencing point for each vertex
  75253. [0, 1, 2].forEach(function (idx) {
  75254. var id = originalIndices[t.originalOffset + idx];
  75255. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75256. if (offset < 0)
  75257. offset = 0;
  75258. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75259. });
  75260. }
  75261. //overwriting the old vertex buffers and indices.
  75262. this._reconstructedMesh.setIndices(newIndicesArray);
  75263. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75264. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75265. if (newUVsData.length > 0)
  75266. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75267. if (newColorsData.length > 0)
  75268. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75269. //create submesh
  75270. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75271. if (submeshIndex > 0) {
  75272. this._reconstructedMesh.subMeshes = [];
  75273. submeshesArray.forEach(function (submesh) {
  75274. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75275. });
  75276. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75277. }
  75278. };
  75279. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75280. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75281. this._reconstructedMesh.material = this._mesh.material;
  75282. this._reconstructedMesh.parent = this._mesh.parent;
  75283. this._reconstructedMesh.isVisible = false;
  75284. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75285. };
  75286. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75287. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75288. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75289. if (t.deleted)
  75290. continue;
  75291. var s = this.references[vertex1.triangleStart + i].vertexId;
  75292. var v1 = t.vertices[(s + 1) % 3];
  75293. var v2 = t.vertices[(s + 2) % 3];
  75294. if ((v1 === vertex2 || v2 === vertex2)) {
  75295. deletedArray[i] = true;
  75296. delTr.push(t);
  75297. continue;
  75298. }
  75299. var d1 = v1.position.subtract(point);
  75300. d1 = d1.normalize();
  75301. var d2 = v2.position.subtract(point);
  75302. d2 = d2.normalize();
  75303. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75304. return true;
  75305. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75306. deletedArray[i] = false;
  75307. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75308. return true;
  75309. }
  75310. return false;
  75311. };
  75312. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75313. var newDeleted = deletedTriangles;
  75314. for (var i = 0; i < vertex.triangleCount; ++i) {
  75315. var ref = this.references[vertex.triangleStart + i];
  75316. var t = this.triangles[ref.triangleId];
  75317. if (t.deleted)
  75318. continue;
  75319. if (deletedArray[i] && t.deletePending) {
  75320. t.deleted = true;
  75321. newDeleted++;
  75322. continue;
  75323. }
  75324. t.vertices[ref.vertexId] = origVertex;
  75325. t.isDirty = true;
  75326. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75327. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75328. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75329. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75330. this.references.push(ref);
  75331. }
  75332. return newDeleted;
  75333. };
  75334. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75335. for (var i = 0; i < this.vertices.length; ++i) {
  75336. var vCount = [];
  75337. var vId = [];
  75338. var v = this.vertices[i];
  75339. var j;
  75340. for (j = 0; j < v.triangleCount; ++j) {
  75341. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75342. for (var ii = 0; ii < 3; ii++) {
  75343. var ofs = 0;
  75344. var vv = triangle.vertices[ii];
  75345. while (ofs < vCount.length) {
  75346. if (vId[ofs] === vv.id)
  75347. break;
  75348. ++ofs;
  75349. }
  75350. if (ofs === vCount.length) {
  75351. vCount.push(1);
  75352. vId.push(vv.id);
  75353. }
  75354. else {
  75355. vCount[ofs]++;
  75356. }
  75357. }
  75358. }
  75359. for (j = 0; j < vCount.length; ++j) {
  75360. if (vCount[j] === 1) {
  75361. this.vertices[vId[j]].isBorder = true;
  75362. }
  75363. else {
  75364. this.vertices[vId[j]].isBorder = false;
  75365. }
  75366. }
  75367. }
  75368. };
  75369. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75370. if (identifyBorders === void 0) { identifyBorders = false; }
  75371. var i;
  75372. if (!identifyBorders) {
  75373. var newTrianglesVector = [];
  75374. for (i = 0; i < this.triangles.length; ++i) {
  75375. if (!this.triangles[i].deleted) {
  75376. newTrianglesVector.push(this.triangles[i]);
  75377. }
  75378. }
  75379. this.triangles = newTrianglesVector;
  75380. }
  75381. for (i = 0; i < this.vertices.length; ++i) {
  75382. this.vertices[i].triangleCount = 0;
  75383. this.vertices[i].triangleStart = 0;
  75384. }
  75385. var t;
  75386. var j;
  75387. var v;
  75388. for (i = 0; i < this.triangles.length; ++i) {
  75389. t = this.triangles[i];
  75390. for (j = 0; j < 3; ++j) {
  75391. v = t.vertices[j];
  75392. v.triangleCount++;
  75393. }
  75394. }
  75395. var tStart = 0;
  75396. for (i = 0; i < this.vertices.length; ++i) {
  75397. this.vertices[i].triangleStart = tStart;
  75398. tStart += this.vertices[i].triangleCount;
  75399. this.vertices[i].triangleCount = 0;
  75400. }
  75401. var newReferences = new Array(this.triangles.length * 3);
  75402. for (i = 0; i < this.triangles.length; ++i) {
  75403. t = this.triangles[i];
  75404. for (j = 0; j < 3; ++j) {
  75405. v = t.vertices[j];
  75406. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75407. v.triangleCount++;
  75408. }
  75409. }
  75410. this.references = newReferences;
  75411. if (identifyBorders) {
  75412. this.identifyBorder();
  75413. }
  75414. };
  75415. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75416. var x = point.x;
  75417. var y = point.y;
  75418. var z = point.z;
  75419. 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
  75420. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75421. };
  75422. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75423. var q = vertex1.q.add(vertex2.q);
  75424. var border = vertex1.isBorder && vertex2.isBorder;
  75425. var error = 0;
  75426. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75427. if (qDet !== 0 && !border) {
  75428. if (!pointResult) {
  75429. pointResult = BABYLON.Vector3.Zero();
  75430. }
  75431. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75432. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75433. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75434. error = this.vertexError(q, pointResult);
  75435. }
  75436. else {
  75437. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75438. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75439. var error1 = this.vertexError(q, vertex1.position);
  75440. var error2 = this.vertexError(q, vertex2.position);
  75441. var error3 = this.vertexError(q, p3);
  75442. error = Math.min(error1, error2, error3);
  75443. if (error === error1) {
  75444. if (pointResult) {
  75445. pointResult.copyFrom(vertex1.position);
  75446. }
  75447. }
  75448. else if (error === error2) {
  75449. if (pointResult) {
  75450. pointResult.copyFrom(vertex2.position);
  75451. }
  75452. }
  75453. else {
  75454. if (pointResult) {
  75455. pointResult.copyFrom(p3);
  75456. }
  75457. }
  75458. }
  75459. return error;
  75460. };
  75461. return QuadraticErrorSimplification;
  75462. }());
  75463. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75464. })(BABYLON || (BABYLON = {}));
  75465. //# sourceMappingURL=babylon.meshSimplification.js.map
  75466. var BABYLON;
  75467. (function (BABYLON) {
  75468. var MeshLODLevel = /** @class */ (function () {
  75469. function MeshLODLevel(distance, mesh) {
  75470. this.distance = distance;
  75471. this.mesh = mesh;
  75472. }
  75473. return MeshLODLevel;
  75474. }());
  75475. BABYLON.MeshLODLevel = MeshLODLevel;
  75476. })(BABYLON || (BABYLON = {}));
  75477. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75478. var BABYLON;
  75479. (function (BABYLON) {
  75480. /**
  75481. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75482. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75483. */
  75484. var SceneOptimization = /** @class */ (function () {
  75485. /**
  75486. * Creates the SceneOptimization object
  75487. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75488. * @param desc defines the description associated with the optimization
  75489. */
  75490. function SceneOptimization(priority) {
  75491. if (priority === void 0) { priority = 0; }
  75492. this.priority = priority;
  75493. }
  75494. /**
  75495. * Gets a string describing the action executed by the current optimization
  75496. */
  75497. SceneOptimization.prototype.getDescription = function () {
  75498. return "";
  75499. };
  75500. /**
  75501. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75502. * @param scene defines the current scene where to apply this optimization
  75503. * @returnstrue if everything that can be done was applied
  75504. */
  75505. SceneOptimization.prototype.apply = function (scene) {
  75506. return true;
  75507. };
  75508. ;
  75509. return SceneOptimization;
  75510. }());
  75511. BABYLON.SceneOptimization = SceneOptimization;
  75512. /**
  75513. * Defines an optimization used to reduce the size of render target textures
  75514. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75515. */
  75516. var TextureOptimization = /** @class */ (function (_super) {
  75517. __extends(TextureOptimization, _super);
  75518. /**
  75519. * Creates the TextureOptimization object
  75520. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75521. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  75522. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75523. */
  75524. function TextureOptimization(priority, maximumSize, step) {
  75525. if (priority === void 0) { priority = 0; }
  75526. if (maximumSize === void 0) { maximumSize = 1024; }
  75527. if (step === void 0) { step = 0.5; }
  75528. var _this = _super.call(this, priority) || this;
  75529. _this.priority = priority;
  75530. _this.maximumSize = maximumSize;
  75531. _this.step = step;
  75532. return _this;
  75533. }
  75534. /**
  75535. * Gets a string describing the action executed by the current optimization
  75536. */
  75537. TextureOptimization.prototype.getDescription = function () {
  75538. return "Reducing render target texture size to " + this.maximumSize;
  75539. };
  75540. /**
  75541. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75542. * @param scene defines the current scene where to apply this optimization
  75543. */
  75544. TextureOptimization.prototype.apply = function (scene) {
  75545. var allDone = true;
  75546. for (var index = 0; index < scene.textures.length; index++) {
  75547. var texture = scene.textures[index];
  75548. if (!texture.canRescale || texture.getContext) {
  75549. continue;
  75550. }
  75551. var currentSize = texture.getSize();
  75552. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75553. if (maxDimension > this.maximumSize) {
  75554. texture.scale(this.step);
  75555. allDone = false;
  75556. }
  75557. }
  75558. return allDone;
  75559. };
  75560. return TextureOptimization;
  75561. }(SceneOptimization));
  75562. BABYLON.TextureOptimization = TextureOptimization;
  75563. /**
  75564. * Defines an optimization used to increase or decrease the rendering resolution
  75565. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75566. */
  75567. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75568. __extends(HardwareScalingOptimization, _super);
  75569. /**
  75570. * Creates the HardwareScalingOptimization object
  75571. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75572. * @param maximumScale
  75573. * @param step
  75574. */
  75575. function HardwareScalingOptimization(priority, maximumScale, step) {
  75576. if (priority === void 0) { priority = 0; }
  75577. if (maximumScale === void 0) { maximumScale = 2; }
  75578. if (step === void 0) { step = 0.25; }
  75579. var _this = _super.call(this, priority) || this;
  75580. _this.priority = priority;
  75581. _this.maximumScale = maximumScale;
  75582. _this.step = step;
  75583. _this._currentScale = -1;
  75584. _this._directionOffset = 1;
  75585. return _this;
  75586. }
  75587. /**
  75588. * Gets a string describing the action executed by the current optimization
  75589. */
  75590. HardwareScalingOptimization.prototype.getDescription = function () {
  75591. return "Setting hardware scaling level to " + this._currentScale;
  75592. };
  75593. /**
  75594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75595. * @param scene defines the current scene where to apply this optimization
  75596. */
  75597. HardwareScalingOptimization.prototype.apply = function (scene) {
  75598. if (this._currentScale === -1) {
  75599. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75600. if (this._currentScale > this.maximumScale) {
  75601. this._directionOffset = -1;
  75602. }
  75603. }
  75604. this._currentScale += this._directionOffset * this.step;
  75605. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75606. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75607. };
  75608. ;
  75609. return HardwareScalingOptimization;
  75610. }(SceneOptimization));
  75611. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75612. /**
  75613. * Defines an optimization used to remove shadows
  75614. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75615. */
  75616. var ShadowsOptimization = /** @class */ (function (_super) {
  75617. __extends(ShadowsOptimization, _super);
  75618. function ShadowsOptimization() {
  75619. return _super !== null && _super.apply(this, arguments) || this;
  75620. }
  75621. /**
  75622. * Gets a string describing the action executed by the current optimization
  75623. */
  75624. ShadowsOptimization.prototype.getDescription = function () {
  75625. return "Turning shadows off";
  75626. };
  75627. /**
  75628. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75629. * @param scene defines the current scene where to apply this optimization
  75630. */
  75631. ShadowsOptimization.prototype.apply = function (scene) {
  75632. scene.shadowsEnabled = false;
  75633. return true;
  75634. };
  75635. ;
  75636. return ShadowsOptimization;
  75637. }(SceneOptimization));
  75638. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75639. /**
  75640. * Defines an optimization used to turn post-processes off
  75641. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75642. */
  75643. var PostProcessesOptimization = /** @class */ (function (_super) {
  75644. __extends(PostProcessesOptimization, _super);
  75645. function PostProcessesOptimization() {
  75646. return _super !== null && _super.apply(this, arguments) || this;
  75647. }
  75648. /**
  75649. * Gets a string describing the action executed by the current optimization
  75650. */
  75651. PostProcessesOptimization.prototype.getDescription = function () {
  75652. return "Turning post-processes off";
  75653. };
  75654. /**
  75655. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75656. * @param scene defines the current scene where to apply this optimization
  75657. */
  75658. PostProcessesOptimization.prototype.apply = function (scene) {
  75659. scene.postProcessesEnabled = false;
  75660. return true;
  75661. };
  75662. ;
  75663. return PostProcessesOptimization;
  75664. }(SceneOptimization));
  75665. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75666. /**
  75667. * Defines an optimization used to turn lens flares off
  75668. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75669. */
  75670. var LensFlaresOptimization = /** @class */ (function (_super) {
  75671. __extends(LensFlaresOptimization, _super);
  75672. function LensFlaresOptimization() {
  75673. return _super !== null && _super.apply(this, arguments) || this;
  75674. }
  75675. /**
  75676. * Gets a string describing the action executed by the current optimization
  75677. */
  75678. LensFlaresOptimization.prototype.getDescription = function () {
  75679. return "Turning lens flares off";
  75680. };
  75681. /**
  75682. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75683. * @param scene defines the current scene where to apply this optimization
  75684. */
  75685. LensFlaresOptimization.prototype.apply = function (scene) {
  75686. scene.lensFlaresEnabled = false;
  75687. return true;
  75688. };
  75689. ;
  75690. return LensFlaresOptimization;
  75691. }(SceneOptimization));
  75692. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75693. /**
  75694. * Defines an optimization based on user defined callback.
  75695. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75696. */
  75697. var CustomOptimization = /** @class */ (function (_super) {
  75698. __extends(CustomOptimization, _super);
  75699. function CustomOptimization() {
  75700. return _super !== null && _super.apply(this, arguments) || this;
  75701. }
  75702. /**
  75703. * Gets a string describing the action executed by the current optimization
  75704. */
  75705. CustomOptimization.prototype.getDescription = function () {
  75706. if (this.onGetDescription) {
  75707. return this.onGetDescription();
  75708. }
  75709. return "Running user defined callback";
  75710. };
  75711. /**
  75712. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75713. * @param scene defines the current scene where to apply this optimization
  75714. */
  75715. CustomOptimization.prototype.apply = function (scene) {
  75716. if (this.onApply) {
  75717. return this.onApply(scene);
  75718. }
  75719. return true;
  75720. };
  75721. ;
  75722. return CustomOptimization;
  75723. }(SceneOptimization));
  75724. BABYLON.CustomOptimization = CustomOptimization;
  75725. /**
  75726. * Defines an optimization used to turn particles off
  75727. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75728. */
  75729. var ParticlesOptimization = /** @class */ (function (_super) {
  75730. __extends(ParticlesOptimization, _super);
  75731. function ParticlesOptimization() {
  75732. return _super !== null && _super.apply(this, arguments) || this;
  75733. }
  75734. /**
  75735. * Gets a string describing the action executed by the current optimization
  75736. */
  75737. ParticlesOptimization.prototype.getDescription = function () {
  75738. return "Turning particles off";
  75739. };
  75740. /**
  75741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75742. * @param scene defines the current scene where to apply this optimization
  75743. */
  75744. ParticlesOptimization.prototype.apply = function (scene) {
  75745. scene.particlesEnabled = false;
  75746. return true;
  75747. };
  75748. ;
  75749. return ParticlesOptimization;
  75750. }(SceneOptimization));
  75751. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75752. /**
  75753. * Defines an optimization used to turn render targets off
  75754. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75755. */
  75756. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75757. __extends(RenderTargetsOptimization, _super);
  75758. function RenderTargetsOptimization() {
  75759. return _super !== null && _super.apply(this, arguments) || this;
  75760. }
  75761. /**
  75762. * Gets a string describing the action executed by the current optimization
  75763. */
  75764. RenderTargetsOptimization.prototype.getDescription = function () {
  75765. return "Turning render targets off";
  75766. };
  75767. /**
  75768. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75769. * @param scene defines the current scene where to apply this optimization
  75770. */
  75771. RenderTargetsOptimization.prototype.apply = function (scene) {
  75772. scene.renderTargetsEnabled = false;
  75773. return true;
  75774. };
  75775. ;
  75776. return RenderTargetsOptimization;
  75777. }(SceneOptimization));
  75778. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75779. /**
  75780. * Defines an optimization used to merge meshes with compatible materials
  75781. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75782. */
  75783. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75784. __extends(MergeMeshesOptimization, _super);
  75785. function MergeMeshesOptimization() {
  75786. var _this = _super !== null && _super.apply(this, arguments) || this;
  75787. _this._canBeMerged = function (abstractMesh) {
  75788. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75789. return false;
  75790. }
  75791. var mesh = abstractMesh;
  75792. if (!mesh.isVisible || !mesh.isEnabled()) {
  75793. return false;
  75794. }
  75795. if (mesh.instances.length > 0) {
  75796. return false;
  75797. }
  75798. if (mesh.skeleton || mesh.hasLODLevels) {
  75799. return false;
  75800. }
  75801. if (mesh.parent) {
  75802. return false;
  75803. }
  75804. return true;
  75805. };
  75806. return _this;
  75807. }
  75808. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75809. /**
  75810. * Gets or sets a boolean which defines if optimization octree has to be updated
  75811. */
  75812. get: function () {
  75813. return MergeMeshesOptimization._UpdateSelectionTree;
  75814. },
  75815. /**
  75816. * Gets or sets a boolean which defines if optimization octree has to be updated
  75817. */
  75818. set: function (value) {
  75819. MergeMeshesOptimization._UpdateSelectionTree = value;
  75820. },
  75821. enumerable: true,
  75822. configurable: true
  75823. });
  75824. /**
  75825. * Gets a string describing the action executed by the current optimization
  75826. */
  75827. MergeMeshesOptimization.prototype.getDescription = function () {
  75828. return "Merging similar meshes together";
  75829. };
  75830. /**
  75831. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75832. * @param scene defines the current scene where to apply this optimization
  75833. */
  75834. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75835. var globalPool = scene.meshes.slice(0);
  75836. var globalLength = globalPool.length;
  75837. for (var index = 0; index < globalLength; index++) {
  75838. var currentPool = new Array();
  75839. var current = globalPool[index];
  75840. // Checks
  75841. if (!this._canBeMerged(current)) {
  75842. continue;
  75843. }
  75844. currentPool.push(current);
  75845. // Find compatible meshes
  75846. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75847. var otherMesh = globalPool[subIndex];
  75848. if (!this._canBeMerged(otherMesh)) {
  75849. continue;
  75850. }
  75851. if (otherMesh.material !== current.material) {
  75852. continue;
  75853. }
  75854. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75855. continue;
  75856. }
  75857. currentPool.push(otherMesh);
  75858. globalLength--;
  75859. globalPool.splice(subIndex, 1);
  75860. subIndex--;
  75861. }
  75862. if (currentPool.length < 2) {
  75863. continue;
  75864. }
  75865. // Merge meshes
  75866. BABYLON.Mesh.MergeMeshes(currentPool);
  75867. }
  75868. if (updateSelectionTree != undefined) {
  75869. if (updateSelectionTree) {
  75870. scene.createOrUpdateSelectionOctree();
  75871. }
  75872. }
  75873. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75874. scene.createOrUpdateSelectionOctree();
  75875. }
  75876. return true;
  75877. };
  75878. ;
  75879. MergeMeshesOptimization._UpdateSelectionTree = false;
  75880. return MergeMeshesOptimization;
  75881. }(SceneOptimization));
  75882. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75883. /**
  75884. * Defines a list of options used by SceneOptimizer
  75885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75886. */
  75887. var SceneOptimizerOptions = /** @class */ (function () {
  75888. /**
  75889. * Creates a new list of options used by SceneOptimizer
  75890. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  75891. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  75892. */
  75893. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75894. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75895. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75896. this.targetFrameRate = targetFrameRate;
  75897. this.trackerDuration = trackerDuration;
  75898. /**
  75899. * Gets the list of optimizations to apply
  75900. */
  75901. this.optimizations = new Array();
  75902. }
  75903. /**
  75904. * Add a new optimization
  75905. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  75906. */
  75907. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  75908. this.optimizations.push(optimization);
  75909. return this;
  75910. };
  75911. /**
  75912. * Add a new custom optimization
  75913. * @param onApply defines the callback called to apply the custom optimization.
  75914. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  75915. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75916. */
  75917. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  75918. if (priority === void 0) { priority = 0; }
  75919. var optimization = new CustomOptimization(priority);
  75920. optimization.onApply = onApply;
  75921. optimization.onGetDescription = onGetDescription;
  75922. this.optimizations.push(optimization);
  75923. return this;
  75924. };
  75925. /**
  75926. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  75927. * @param targetFrameRate defines the target frame rate (60 by default)
  75928. * @returns a SceneOptimizerOptions object
  75929. */
  75930. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75931. var result = new SceneOptimizerOptions(targetFrameRate);
  75932. var priority = 0;
  75933. result.addOptimization(new MergeMeshesOptimization(priority));
  75934. result.addOptimization(new ShadowsOptimization(priority));
  75935. result.addOptimization(new LensFlaresOptimization(priority));
  75936. // Next priority
  75937. priority++;
  75938. result.addOptimization(new PostProcessesOptimization(priority));
  75939. result.addOptimization(new ParticlesOptimization(priority));
  75940. // Next priority
  75941. priority++;
  75942. result.addOptimization(new TextureOptimization(priority, 1024));
  75943. return result;
  75944. };
  75945. /**
  75946. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  75947. * @param targetFrameRate defines the target frame rate (60 by default)
  75948. * @returns a SceneOptimizerOptions object
  75949. */
  75950. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75951. var result = new SceneOptimizerOptions(targetFrameRate);
  75952. var priority = 0;
  75953. result.addOptimization(new MergeMeshesOptimization(priority));
  75954. result.addOptimization(new ShadowsOptimization(priority));
  75955. result.addOptimization(new LensFlaresOptimization(priority));
  75956. // Next priority
  75957. priority++;
  75958. result.addOptimization(new PostProcessesOptimization(priority));
  75959. result.addOptimization(new ParticlesOptimization(priority));
  75960. // Next priority
  75961. priority++;
  75962. result.addOptimization(new TextureOptimization(priority, 512));
  75963. // Next priority
  75964. priority++;
  75965. result.addOptimization(new RenderTargetsOptimization(priority));
  75966. // Next priority
  75967. priority++;
  75968. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  75969. return result;
  75970. };
  75971. /**
  75972. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  75973. * @param targetFrameRate defines the target frame rate (60 by default)
  75974. * @returns a SceneOptimizerOptions object
  75975. */
  75976. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75977. var result = new SceneOptimizerOptions(targetFrameRate);
  75978. var priority = 0;
  75979. result.addOptimization(new MergeMeshesOptimization(priority));
  75980. result.addOptimization(new ShadowsOptimization(priority));
  75981. result.addOptimization(new LensFlaresOptimization(priority));
  75982. // Next priority
  75983. priority++;
  75984. result.addOptimization(new PostProcessesOptimization(priority));
  75985. result.addOptimization(new ParticlesOptimization(priority));
  75986. // Next priority
  75987. priority++;
  75988. result.addOptimization(new TextureOptimization(priority, 256));
  75989. // Next priority
  75990. priority++;
  75991. result.addOptimization(new RenderTargetsOptimization(priority));
  75992. // Next priority
  75993. priority++;
  75994. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  75995. return result;
  75996. };
  75997. return SceneOptimizerOptions;
  75998. }());
  75999. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76000. /**
  76001. * Class used to run optimizations in order to reach a target frame rate
  76002. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76003. */
  76004. var SceneOptimizer = /** @class */ (function () {
  76005. /**
  76006. * Creates a new SceneOptimizer
  76007. * @param scene defines the scene to work on
  76008. * @param options defines the options to use with the SceneOptimizer
  76009. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76010. */
  76011. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76012. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76013. var _this = this;
  76014. this._isRunning = false;
  76015. this._currentPriorityLevel = 0;
  76016. this._targetFrameRate = 60;
  76017. this._trackerDuration = 2000;
  76018. this._currentFrameRate = 0;
  76019. /**
  76020. * Defines an observable called when the optimizer reaches the target frame rate
  76021. */
  76022. this.onSuccessObservable = new BABYLON.Observable();
  76023. /**
  76024. * Defines an observable called when the optimizer enables an optimization
  76025. */
  76026. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76027. /**
  76028. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76029. */
  76030. this.onFailureObservable = new BABYLON.Observable();
  76031. if (!options) {
  76032. this._options = new SceneOptimizerOptions();
  76033. }
  76034. else {
  76035. this._options = options;
  76036. }
  76037. if (this._options.targetFrameRate) {
  76038. this._targetFrameRate = this._options.targetFrameRate;
  76039. }
  76040. if (this._options.trackerDuration) {
  76041. this._trackerDuration = this._options.trackerDuration;
  76042. }
  76043. if (autoGeneratePriorities) {
  76044. var priority = 0;
  76045. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76046. var optim = _a[_i];
  76047. optim.priority = priority++;
  76048. }
  76049. }
  76050. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76051. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76052. _this._sceneDisposeObserver = null;
  76053. _this.dispose();
  76054. });
  76055. }
  76056. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76057. /**
  76058. * Gets the current priority level (0 at start)
  76059. */
  76060. get: function () {
  76061. return this._currentPriorityLevel;
  76062. },
  76063. enumerable: true,
  76064. configurable: true
  76065. });
  76066. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76067. /**
  76068. * Gets the current frame rate checked by the SceneOptimizer
  76069. */
  76070. get: function () {
  76071. return this._currentFrameRate;
  76072. },
  76073. enumerable: true,
  76074. configurable: true
  76075. });
  76076. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76077. /**
  76078. * Gets or sets the current target frame rate (60 by default)
  76079. */
  76080. get: function () {
  76081. return this._targetFrameRate;
  76082. },
  76083. /**
  76084. * Gets or sets the current target frame rate (60 by default)
  76085. */
  76086. set: function (value) {
  76087. this._targetFrameRate = value;
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76093. /**
  76094. * Gets or sets the current interval between two checks (every 2000ms by default)
  76095. */
  76096. get: function () {
  76097. return this._trackerDuration;
  76098. },
  76099. /**
  76100. * Gets or sets the current interval between two checks (every 2000ms by default)
  76101. */
  76102. set: function (value) {
  76103. this._trackerDuration = value;
  76104. },
  76105. enumerable: true,
  76106. configurable: true
  76107. });
  76108. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76109. /**
  76110. * Gets the list of active optimizations
  76111. */
  76112. get: function () {
  76113. return this._options.optimizations;
  76114. },
  76115. enumerable: true,
  76116. configurable: true
  76117. });
  76118. /**
  76119. * Stops the current optimizer
  76120. */
  76121. SceneOptimizer.prototype.stop = function () {
  76122. this._isRunning = false;
  76123. };
  76124. SceneOptimizer.prototype.reset = function () {
  76125. this._currentPriorityLevel = 0;
  76126. };
  76127. SceneOptimizer.prototype.start = function () {
  76128. var _this = this;
  76129. if (this._isRunning) {
  76130. return;
  76131. }
  76132. this._isRunning = true;
  76133. // Let's wait for the scene to be ready before running our check
  76134. this._scene.executeWhenReady(function () {
  76135. setTimeout(function () {
  76136. _this._checkCurrentState();
  76137. }, _this._trackerDuration);
  76138. });
  76139. };
  76140. SceneOptimizer.prototype._checkCurrentState = function () {
  76141. var _this = this;
  76142. if (!this._isRunning) {
  76143. return;
  76144. }
  76145. var scene = this._scene;
  76146. var options = this._options;
  76147. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76148. if (this._currentFrameRate >= this._targetFrameRate) {
  76149. this._isRunning = false;
  76150. this.onSuccessObservable.notifyObservers(this);
  76151. return;
  76152. }
  76153. // Apply current level of optimizations
  76154. var allDone = true;
  76155. var noOptimizationApplied = true;
  76156. for (var index = 0; index < options.optimizations.length; index++) {
  76157. var optimization = options.optimizations[index];
  76158. if (optimization.priority === this._currentPriorityLevel) {
  76159. noOptimizationApplied = false;
  76160. allDone = allDone && optimization.apply(scene);
  76161. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76162. }
  76163. }
  76164. // If no optimization was applied, this is a failure :(
  76165. if (noOptimizationApplied) {
  76166. this._isRunning = false;
  76167. this.onFailureObservable.notifyObservers(this);
  76168. return;
  76169. }
  76170. // If all optimizations were done, move to next level
  76171. if (allDone) {
  76172. this._currentPriorityLevel++;
  76173. }
  76174. // Let's the system running for a specific amount of time before checking FPS
  76175. scene.executeWhenReady(function () {
  76176. setTimeout(function () {
  76177. _this._checkCurrentState();
  76178. }, _this._trackerDuration);
  76179. });
  76180. };
  76181. /**
  76182. * Release all resources
  76183. */
  76184. SceneOptimizer.prototype.dispose = function () {
  76185. this.stop();
  76186. this.onSuccessObservable.clear();
  76187. this.onFailureObservable.clear();
  76188. this.onNewOptimizationAppliedObservable.clear();
  76189. if (this._sceneDisposeObserver) {
  76190. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76191. }
  76192. };
  76193. /**
  76194. * Helper function to create a SceneOptimizer with one single line of code
  76195. * @param scene defines the scene to work on
  76196. * @param options defines the options to use with the SceneOptimizer
  76197. * @param onSuccess defines a callback to call on success
  76198. * @param onFailure defines a callback to call on failure
  76199. */
  76200. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76201. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76202. if (onSuccess) {
  76203. optimizer.onSuccessObservable.add(function () {
  76204. onSuccess();
  76205. });
  76206. }
  76207. if (onFailure) {
  76208. optimizer.onFailureObservable.add(function () {
  76209. onFailure();
  76210. });
  76211. }
  76212. optimizer.start();
  76213. return optimizer;
  76214. };
  76215. return SceneOptimizer;
  76216. }());
  76217. BABYLON.SceneOptimizer = SceneOptimizer;
  76218. })(BABYLON || (BABYLON = {}));
  76219. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76220. var BABYLON;
  76221. (function (BABYLON) {
  76222. var OutlineRenderer = /** @class */ (function () {
  76223. function OutlineRenderer(scene) {
  76224. this.zOffset = 1;
  76225. this._scene = scene;
  76226. }
  76227. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76228. var _this = this;
  76229. if (useOverlay === void 0) { useOverlay = false; }
  76230. var scene = this._scene;
  76231. var engine = this._scene.getEngine();
  76232. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76233. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76234. return;
  76235. }
  76236. var mesh = subMesh.getRenderingMesh();
  76237. var material = subMesh.getMaterial();
  76238. if (!material || !scene.activeCamera) {
  76239. return;
  76240. }
  76241. engine.enableEffect(this._effect);
  76242. // Logarithmic depth
  76243. if (material.useLogarithmicDepth) {
  76244. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76245. }
  76246. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76247. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76248. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76249. // Bones
  76250. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76251. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76252. }
  76253. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76254. // Alpha test
  76255. if (material && material.needAlphaTesting()) {
  76256. var alphaTexture = material.getAlphaTestTexture();
  76257. if (alphaTexture) {
  76258. this._effect.setTexture("diffuseSampler", alphaTexture);
  76259. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76260. }
  76261. }
  76262. engine.setZOffset(-this.zOffset);
  76263. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76264. engine.setZOffset(0);
  76265. };
  76266. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76267. var defines = [];
  76268. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76269. var mesh = subMesh.getMesh();
  76270. var material = subMesh.getMaterial();
  76271. if (material) {
  76272. // Alpha test
  76273. if (material.needAlphaTesting()) {
  76274. defines.push("#define ALPHATEST");
  76275. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76276. attribs.push(BABYLON.VertexBuffer.UVKind);
  76277. defines.push("#define UV1");
  76278. }
  76279. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76280. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76281. defines.push("#define UV2");
  76282. }
  76283. }
  76284. //Logarithmic depth
  76285. if (material.useLogarithmicDepth) {
  76286. defines.push("#define LOGARITHMICDEPTH");
  76287. }
  76288. }
  76289. // Bones
  76290. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76293. if (mesh.numBoneInfluencers > 4) {
  76294. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76295. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76296. }
  76297. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76298. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76299. }
  76300. else {
  76301. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76302. }
  76303. // Instances
  76304. if (useInstances) {
  76305. defines.push("#define INSTANCES");
  76306. attribs.push("world0");
  76307. attribs.push("world1");
  76308. attribs.push("world2");
  76309. attribs.push("world3");
  76310. }
  76311. // Get correct effect
  76312. var join = defines.join("\n");
  76313. if (this._cachedDefines !== join) {
  76314. this._cachedDefines = join;
  76315. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76316. }
  76317. return this._effect.isReady();
  76318. };
  76319. return OutlineRenderer;
  76320. }());
  76321. BABYLON.OutlineRenderer = OutlineRenderer;
  76322. })(BABYLON || (BABYLON = {}));
  76323. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76324. var BABYLON;
  76325. (function (BABYLON) {
  76326. var FaceAdjacencies = /** @class */ (function () {
  76327. function FaceAdjacencies() {
  76328. this.edges = new Array();
  76329. this.edgesConnectedCount = 0;
  76330. }
  76331. return FaceAdjacencies;
  76332. }());
  76333. var EdgesRenderer = /** @class */ (function () {
  76334. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76335. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76336. if (epsilon === void 0) { epsilon = 0.95; }
  76337. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76338. this.edgesWidthScalerForOrthographic = 1000.0;
  76339. this.edgesWidthScalerForPerspective = 50.0;
  76340. this._linesPositions = new Array();
  76341. this._linesNormals = new Array();
  76342. this._linesIndices = new Array();
  76343. this._buffers = {};
  76344. this._checkVerticesInsteadOfIndices = false;
  76345. this._source = source;
  76346. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76347. this._epsilon = epsilon;
  76348. this._prepareRessources();
  76349. this._generateEdgesLines();
  76350. }
  76351. EdgesRenderer.prototype._prepareRessources = function () {
  76352. if (this._lineShader) {
  76353. return;
  76354. }
  76355. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76356. attributes: ["position", "normal"],
  76357. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76358. });
  76359. this._lineShader.disableDepthWrite = true;
  76360. this._lineShader.backFaceCulling = false;
  76361. };
  76362. EdgesRenderer.prototype._rebuild = function () {
  76363. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76364. if (buffer) {
  76365. buffer._rebuild();
  76366. }
  76367. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76368. if (buffer) {
  76369. buffer._rebuild();
  76370. }
  76371. var scene = this._source.getScene();
  76372. var engine = scene.getEngine();
  76373. this._ib = engine.createIndexBuffer(this._linesIndices);
  76374. };
  76375. EdgesRenderer.prototype.dispose = function () {
  76376. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76377. if (buffer) {
  76378. buffer.dispose();
  76379. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76380. }
  76381. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76382. if (buffer) {
  76383. buffer.dispose();
  76384. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76385. }
  76386. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76387. this._lineShader.dispose();
  76388. };
  76389. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76390. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76391. return 0;
  76392. }
  76393. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76394. return 1;
  76395. }
  76396. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76397. return 2;
  76398. }
  76399. return -1;
  76400. };
  76401. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76402. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76403. return 0;
  76404. }
  76405. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76406. return 1;
  76407. }
  76408. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76409. return 2;
  76410. }
  76411. return -1;
  76412. };
  76413. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76414. var needToCreateLine;
  76415. if (edge === undefined) {
  76416. needToCreateLine = true;
  76417. }
  76418. else {
  76419. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76420. needToCreateLine = dotProduct < this._epsilon;
  76421. }
  76422. if (needToCreateLine) {
  76423. var offset = this._linesPositions.length / 3;
  76424. var normal = p0.subtract(p1);
  76425. normal.normalize();
  76426. // Positions
  76427. this._linesPositions.push(p0.x);
  76428. this._linesPositions.push(p0.y);
  76429. this._linesPositions.push(p0.z);
  76430. this._linesPositions.push(p0.x);
  76431. this._linesPositions.push(p0.y);
  76432. this._linesPositions.push(p0.z);
  76433. this._linesPositions.push(p1.x);
  76434. this._linesPositions.push(p1.y);
  76435. this._linesPositions.push(p1.z);
  76436. this._linesPositions.push(p1.x);
  76437. this._linesPositions.push(p1.y);
  76438. this._linesPositions.push(p1.z);
  76439. // Normals
  76440. this._linesNormals.push(p1.x);
  76441. this._linesNormals.push(p1.y);
  76442. this._linesNormals.push(p1.z);
  76443. this._linesNormals.push(-1);
  76444. this._linesNormals.push(p1.x);
  76445. this._linesNormals.push(p1.y);
  76446. this._linesNormals.push(p1.z);
  76447. this._linesNormals.push(1);
  76448. this._linesNormals.push(p0.x);
  76449. this._linesNormals.push(p0.y);
  76450. this._linesNormals.push(p0.z);
  76451. this._linesNormals.push(-1);
  76452. this._linesNormals.push(p0.x);
  76453. this._linesNormals.push(p0.y);
  76454. this._linesNormals.push(p0.z);
  76455. this._linesNormals.push(1);
  76456. // Indices
  76457. this._linesIndices.push(offset);
  76458. this._linesIndices.push(offset + 1);
  76459. this._linesIndices.push(offset + 2);
  76460. this._linesIndices.push(offset);
  76461. this._linesIndices.push(offset + 2);
  76462. this._linesIndices.push(offset + 3);
  76463. }
  76464. };
  76465. EdgesRenderer.prototype._generateEdgesLines = function () {
  76466. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76467. var indices = this._source.getIndices();
  76468. if (!indices || !positions) {
  76469. return;
  76470. }
  76471. // First let's find adjacencies
  76472. var adjacencies = new Array();
  76473. var faceNormals = new Array();
  76474. var index;
  76475. var faceAdjacencies;
  76476. // Prepare faces
  76477. for (index = 0; index < indices.length; index += 3) {
  76478. faceAdjacencies = new FaceAdjacencies();
  76479. var p0Index = indices[index];
  76480. var p1Index = indices[index + 1];
  76481. var p2Index = indices[index + 2];
  76482. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76483. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76484. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76485. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76486. faceNormal.normalize();
  76487. faceNormals.push(faceNormal);
  76488. adjacencies.push(faceAdjacencies);
  76489. }
  76490. // Scan
  76491. for (index = 0; index < adjacencies.length; index++) {
  76492. faceAdjacencies = adjacencies[index];
  76493. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76494. var otherFaceAdjacencies = adjacencies[otherIndex];
  76495. if (faceAdjacencies.edgesConnectedCount === 3) {
  76496. break;
  76497. }
  76498. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76499. continue;
  76500. }
  76501. var otherP0 = indices[otherIndex * 3];
  76502. var otherP1 = indices[otherIndex * 3 + 1];
  76503. var otherP2 = indices[otherIndex * 3 + 2];
  76504. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76505. var otherEdgeIndex = 0;
  76506. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76507. continue;
  76508. }
  76509. switch (edgeIndex) {
  76510. case 0:
  76511. if (this._checkVerticesInsteadOfIndices) {
  76512. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76513. }
  76514. else {
  76515. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76516. }
  76517. break;
  76518. case 1:
  76519. if (this._checkVerticesInsteadOfIndices) {
  76520. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76521. }
  76522. else {
  76523. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76524. }
  76525. break;
  76526. case 2:
  76527. if (this._checkVerticesInsteadOfIndices) {
  76528. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76529. }
  76530. else {
  76531. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76532. }
  76533. break;
  76534. }
  76535. if (otherEdgeIndex === -1) {
  76536. continue;
  76537. }
  76538. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76539. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76540. faceAdjacencies.edgesConnectedCount++;
  76541. otherFaceAdjacencies.edgesConnectedCount++;
  76542. if (faceAdjacencies.edgesConnectedCount === 3) {
  76543. break;
  76544. }
  76545. }
  76546. }
  76547. }
  76548. // Create lines
  76549. for (index = 0; index < adjacencies.length; index++) {
  76550. // 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
  76551. var current = adjacencies[index];
  76552. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76553. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76554. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76555. }
  76556. // Merge into a single mesh
  76557. var engine = this._source.getScene().getEngine();
  76558. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76559. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76560. this._ib = engine.createIndexBuffer(this._linesIndices);
  76561. this._indicesCount = this._linesIndices.length;
  76562. };
  76563. EdgesRenderer.prototype.render = function () {
  76564. var scene = this._source.getScene();
  76565. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76566. return;
  76567. }
  76568. var engine = scene.getEngine();
  76569. this._lineShader._preBind();
  76570. // VBOs
  76571. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76572. scene.resetCachedMaterial();
  76573. this._lineShader.setColor4("color", this._source.edgesColor);
  76574. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76575. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76576. }
  76577. else {
  76578. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76579. }
  76580. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76581. this._lineShader.bind(this._source.getWorldMatrix());
  76582. // Draw order
  76583. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76584. this._lineShader.unbind();
  76585. engine.setDepthWrite(true);
  76586. };
  76587. return EdgesRenderer;
  76588. }());
  76589. BABYLON.EdgesRenderer = EdgesRenderer;
  76590. })(BABYLON || (BABYLON = {}));
  76591. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76592. var BABYLON;
  76593. (function (BABYLON) {
  76594. /**
  76595. * Special Glow Blur post process only blurring the alpha channel
  76596. * It enforces keeping the most luminous color in the color channel.
  76597. */
  76598. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76599. __extends(GlowBlurPostProcess, _super);
  76600. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76602. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76603. _this.direction = direction;
  76604. _this.kernel = kernel;
  76605. _this.onApplyObservable.add(function (effect) {
  76606. effect.setFloat2("screenSize", _this.width, _this.height);
  76607. effect.setVector2("direction", _this.direction);
  76608. effect.setFloat("blurWidth", _this.kernel);
  76609. });
  76610. return _this;
  76611. }
  76612. return GlowBlurPostProcess;
  76613. }(BABYLON.PostProcess));
  76614. /**
  76615. * The highlight layer Helps adding a glow effect around a mesh.
  76616. *
  76617. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76618. * glowy meshes to your scene.
  76619. *
  76620. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76621. */
  76622. var HighlightLayer = /** @class */ (function () {
  76623. /**
  76624. * Instantiates a new highlight Layer and references it to the scene..
  76625. * @param name The name of the layer
  76626. * @param scene The scene to use the layer in
  76627. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76628. */
  76629. function HighlightLayer(name, scene, options) {
  76630. this.name = name;
  76631. this._vertexBuffers = {};
  76632. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76633. this._meshes = {};
  76634. this._maxSize = 0;
  76635. this._shouldRender = false;
  76636. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76637. this._excludedMeshes = {};
  76638. /**
  76639. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76640. */
  76641. this.innerGlow = true;
  76642. /**
  76643. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76644. */
  76645. this.outerGlow = true;
  76646. /**
  76647. * Specifies wether the highlight layer is enabled or not.
  76648. */
  76649. this.isEnabled = true;
  76650. /**
  76651. * An event triggered when the highlight layer has been disposed.
  76652. * @type {BABYLON.Observable}
  76653. */
  76654. this.onDisposeObservable = new BABYLON.Observable();
  76655. /**
  76656. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76657. * @type {BABYLON.Observable}
  76658. */
  76659. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76660. /**
  76661. * An event triggered when the highlight layer is being blurred.
  76662. * @type {BABYLON.Observable}
  76663. */
  76664. this.onBeforeBlurObservable = new BABYLON.Observable();
  76665. /**
  76666. * An event triggered when the highlight layer has been blurred.
  76667. * @type {BABYLON.Observable}
  76668. */
  76669. this.onAfterBlurObservable = new BABYLON.Observable();
  76670. /**
  76671. * An event triggered when the glowing blurred texture is being merged in the scene.
  76672. * @type {BABYLON.Observable}
  76673. */
  76674. this.onBeforeComposeObservable = new BABYLON.Observable();
  76675. /**
  76676. * An event triggered when the glowing blurred texture has been merged in the scene.
  76677. * @type {BABYLON.Observable}
  76678. */
  76679. this.onAfterComposeObservable = new BABYLON.Observable();
  76680. /**
  76681. * An event triggered when the highlight layer changes its size.
  76682. * @type {BABYLON.Observable}
  76683. */
  76684. this.onSizeChangedObservable = new BABYLON.Observable();
  76685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76686. var engine = scene.getEngine();
  76687. this._engine = engine;
  76688. this._maxSize = this._engine.getCaps().maxTextureSize;
  76689. this._scene.highlightLayers.push(this);
  76690. // Warn on stencil.
  76691. if (!this._engine.isStencilEnable) {
  76692. 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 }");
  76693. }
  76694. // Adapt options
  76695. this._options = options || {
  76696. mainTextureRatio: 0.5,
  76697. blurTextureSizeRatio: 0.5,
  76698. blurHorizontalSize: 1.0,
  76699. blurVerticalSize: 1.0,
  76700. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76701. camera: null
  76702. };
  76703. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76704. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76705. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76706. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76707. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76708. // VBO
  76709. var vertices = [];
  76710. vertices.push(1, 1);
  76711. vertices.push(-1, 1);
  76712. vertices.push(-1, -1);
  76713. vertices.push(1, -1);
  76714. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76716. this._createIndexBuffer();
  76717. // Effect
  76718. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76719. // Render target
  76720. this.setMainTextureSize();
  76721. // Create Textures and post processes
  76722. this.createTextureAndPostProcesses();
  76723. }
  76724. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76725. /**
  76726. * Gets the horizontal size of the blur.
  76727. */
  76728. get: function () {
  76729. return this._horizontalBlurPostprocess.kernel;
  76730. },
  76731. /**
  76732. * Specifies the horizontal size of the blur.
  76733. */
  76734. set: function (value) {
  76735. this._horizontalBlurPostprocess.kernel = value;
  76736. },
  76737. enumerable: true,
  76738. configurable: true
  76739. });
  76740. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76741. /**
  76742. * Gets the vertical size of the blur.
  76743. */
  76744. get: function () {
  76745. return this._verticalBlurPostprocess.kernel;
  76746. },
  76747. /**
  76748. * Specifies the vertical size of the blur.
  76749. */
  76750. set: function (value) {
  76751. this._verticalBlurPostprocess.kernel = value;
  76752. },
  76753. enumerable: true,
  76754. configurable: true
  76755. });
  76756. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76757. /**
  76758. * Gets the camera attached to the layer.
  76759. */
  76760. get: function () {
  76761. return this._options.camera;
  76762. },
  76763. enumerable: true,
  76764. configurable: true
  76765. });
  76766. HighlightLayer.prototype._createIndexBuffer = function () {
  76767. var engine = this._scene.getEngine();
  76768. // Indices
  76769. var indices = [];
  76770. indices.push(0);
  76771. indices.push(1);
  76772. indices.push(2);
  76773. indices.push(0);
  76774. indices.push(2);
  76775. indices.push(3);
  76776. this._indexBuffer = engine.createIndexBuffer(indices);
  76777. };
  76778. HighlightLayer.prototype._rebuild = function () {
  76779. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76780. if (vb) {
  76781. vb._rebuild();
  76782. }
  76783. this._createIndexBuffer();
  76784. };
  76785. /**
  76786. * Creates the render target textures and post processes used in the highlight layer.
  76787. */
  76788. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76789. var _this = this;
  76790. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76791. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76792. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76793. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76794. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76795. width: this._mainTextureDesiredSize.width,
  76796. height: this._mainTextureDesiredSize.height
  76797. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76798. this._mainTexture.activeCamera = this._options.camera;
  76799. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76800. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76801. this._mainTexture.anisotropicFilteringLevel = 1;
  76802. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76803. this._mainTexture.renderParticles = false;
  76804. this._mainTexture.renderList = null;
  76805. this._mainTexture.ignoreCameraViewport = true;
  76806. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76807. width: blurTextureWidth,
  76808. height: blurTextureHeight
  76809. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76810. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76811. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76812. this._blurTexture.anisotropicFilteringLevel = 16;
  76813. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76814. this._blurTexture.renderParticles = false;
  76815. this._blurTexture.ignoreCameraViewport = true;
  76816. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76817. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76818. effect.setTexture("textureSampler", _this._mainTexture);
  76819. });
  76820. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76821. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76822. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76823. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76824. });
  76825. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76826. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76827. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76828. });
  76829. }
  76830. else {
  76831. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76832. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76833. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76834. });
  76835. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76836. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76837. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76838. });
  76839. }
  76840. this._mainTexture.onAfterUnbindObservable.add(function () {
  76841. _this.onBeforeBlurObservable.notifyObservers(_this);
  76842. var internalTexture = _this._blurTexture.getInternalTexture();
  76843. if (internalTexture) {
  76844. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76845. }
  76846. _this.onAfterBlurObservable.notifyObservers(_this);
  76847. });
  76848. // Custom render function
  76849. var renderSubMesh = function (subMesh) {
  76850. if (!_this._meshes) {
  76851. return;
  76852. }
  76853. var material = subMesh.getMaterial();
  76854. var mesh = subMesh.getRenderingMesh();
  76855. var scene = _this._scene;
  76856. var engine = scene.getEngine();
  76857. if (!material) {
  76858. return;
  76859. }
  76860. // Do not block in blend mode.
  76861. if (material.needAlphaBlendingForMesh(mesh)) {
  76862. return;
  76863. }
  76864. // Culling
  76865. engine.setState(material.backFaceCulling);
  76866. // Managing instances
  76867. var batch = mesh._getInstancesRenderList(subMesh._id);
  76868. if (batch.mustReturn) {
  76869. return;
  76870. }
  76871. // Excluded Mesh
  76872. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76873. return;
  76874. }
  76875. ;
  76876. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76877. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76878. var emissiveTexture = null;
  76879. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76880. emissiveTexture = material.emissiveTexture;
  76881. }
  76882. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76883. engine.enableEffect(_this._glowMapGenerationEffect);
  76884. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76885. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76886. if (highlightLayerMesh) {
  76887. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76888. }
  76889. else {
  76890. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76891. }
  76892. // Alpha test
  76893. if (material && material.needAlphaTesting()) {
  76894. var alphaTexture = material.getAlphaTestTexture();
  76895. if (alphaTexture) {
  76896. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76897. var textureMatrix = alphaTexture.getTextureMatrix();
  76898. if (textureMatrix) {
  76899. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76900. }
  76901. }
  76902. }
  76903. // Glow emissive only
  76904. if (emissiveTexture) {
  76905. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76906. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76907. }
  76908. // Bones
  76909. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76910. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76911. }
  76912. // Draw
  76913. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76914. }
  76915. else {
  76916. // Need to reset refresh rate of the shadowMap
  76917. _this._mainTexture.resetRefreshCounter();
  76918. }
  76919. };
  76920. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76921. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76922. var index;
  76923. var engine = _this._scene.getEngine();
  76924. if (depthOnlySubMeshes.length) {
  76925. engine.setColorWrite(false);
  76926. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76927. renderSubMesh(depthOnlySubMeshes.data[index]);
  76928. }
  76929. engine.setColorWrite(true);
  76930. }
  76931. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76932. renderSubMesh(opaqueSubMeshes.data[index]);
  76933. }
  76934. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76935. renderSubMesh(alphaTestSubMeshes.data[index]);
  76936. }
  76937. for (index = 0; index < transparentSubMeshes.length; index++) {
  76938. renderSubMesh(transparentSubMeshes.data[index]);
  76939. }
  76940. };
  76941. this._mainTexture.onClearObservable.add(function (engine) {
  76942. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76943. });
  76944. };
  76945. /**
  76946. * Checks for the readiness of the element composing the layer.
  76947. * @param subMesh the mesh to check for
  76948. * @param useInstances specify wether or not to use instances to render the mesh
  76949. * @param emissiveTexture the associated emissive texture used to generate the glow
  76950. * @return true if ready otherwise, false
  76951. */
  76952. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  76953. var material = subMesh.getMaterial();
  76954. var mesh = subMesh.getRenderingMesh();
  76955. if (!material || !mesh || !this._meshes) {
  76956. return false;
  76957. }
  76958. var emissiveTexture = null;
  76959. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  76960. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76961. emissiveTexture = material.emissiveTexture;
  76962. }
  76963. return this._isReady(subMesh, useInstances, emissiveTexture);
  76964. };
  76965. /**
  76966. * Checks for the readiness of the element composing the layer.
  76967. * @param subMesh the mesh to check for
  76968. * @param useInstances specify wether or not to use instances to render the mesh
  76969. * @param emissiveTexture the associated emissive texture used to generate the glow
  76970. * @return true if ready otherwise, false
  76971. */
  76972. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  76973. var material = subMesh.getMaterial();
  76974. if (!material) {
  76975. return false;
  76976. }
  76977. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76978. return false;
  76979. }
  76980. var defines = [];
  76981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76982. var mesh = subMesh.getMesh();
  76983. var uv1 = false;
  76984. var uv2 = false;
  76985. // Alpha test
  76986. if (material && material.needAlphaTesting()) {
  76987. var alphaTexture = material.getAlphaTestTexture();
  76988. if (alphaTexture) {
  76989. defines.push("#define ALPHATEST");
  76990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76991. alphaTexture.coordinatesIndex === 1) {
  76992. defines.push("#define DIFFUSEUV2");
  76993. uv2 = true;
  76994. }
  76995. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76996. defines.push("#define DIFFUSEUV1");
  76997. uv1 = true;
  76998. }
  76999. }
  77000. }
  77001. // Emissive
  77002. if (emissiveTexture) {
  77003. defines.push("#define EMISSIVE");
  77004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77005. emissiveTexture.coordinatesIndex === 1) {
  77006. defines.push("#define EMISSIVEUV2");
  77007. uv2 = true;
  77008. }
  77009. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77010. defines.push("#define EMISSIVEUV1");
  77011. uv1 = true;
  77012. }
  77013. }
  77014. if (uv1) {
  77015. attribs.push(BABYLON.VertexBuffer.UVKind);
  77016. defines.push("#define UV1");
  77017. }
  77018. if (uv2) {
  77019. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77020. defines.push("#define UV2");
  77021. }
  77022. // Bones
  77023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77026. if (mesh.numBoneInfluencers > 4) {
  77027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77029. }
  77030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77031. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77032. }
  77033. else {
  77034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77035. }
  77036. // Instances
  77037. if (useInstances) {
  77038. defines.push("#define INSTANCES");
  77039. attribs.push("world0");
  77040. attribs.push("world1");
  77041. attribs.push("world2");
  77042. attribs.push("world3");
  77043. }
  77044. // Get correct effect
  77045. var join = defines.join("\n");
  77046. if (this._cachedDefines !== join) {
  77047. this._cachedDefines = join;
  77048. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77049. }
  77050. return this._glowMapGenerationEffect.isReady();
  77051. };
  77052. /**
  77053. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77054. */
  77055. HighlightLayer.prototype.render = function () {
  77056. var currentEffect = this._glowMapMergeEffect;
  77057. // Check
  77058. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77059. return;
  77060. var engine = this._scene.getEngine();
  77061. this.onBeforeComposeObservable.notifyObservers(this);
  77062. // Render
  77063. engine.enableEffect(currentEffect);
  77064. engine.setState(false);
  77065. // Cache
  77066. var previousStencilBuffer = engine.getStencilBuffer();
  77067. var previousStencilFunction = engine.getStencilFunction();
  77068. var previousStencilMask = engine.getStencilMask();
  77069. var previousStencilOperationPass = engine.getStencilOperationPass();
  77070. var previousStencilOperationFail = engine.getStencilOperationFail();
  77071. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77072. var previousAlphaMode = engine.getAlphaMode();
  77073. // Texture
  77074. currentEffect.setTexture("textureSampler", this._blurTexture);
  77075. // VBOs
  77076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77077. // Stencil operations
  77078. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77079. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77080. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77081. // Draw order
  77082. engine.setAlphaMode(this._options.alphaBlendingMode);
  77083. engine.setStencilMask(0x00);
  77084. engine.setStencilBuffer(true);
  77085. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77086. if (this.outerGlow) {
  77087. currentEffect.setFloat("offset", 0);
  77088. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77089. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77090. }
  77091. if (this.innerGlow) {
  77092. currentEffect.setFloat("offset", 1);
  77093. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77094. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77095. }
  77096. // Restore Cache
  77097. engine.setStencilFunction(previousStencilFunction);
  77098. engine.setStencilMask(previousStencilMask);
  77099. engine.setAlphaMode(previousAlphaMode);
  77100. engine.setStencilBuffer(previousStencilBuffer);
  77101. engine.setStencilOperationPass(previousStencilOperationPass);
  77102. engine.setStencilOperationFail(previousStencilOperationFail);
  77103. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77104. engine._stencilState.reset();
  77105. this.onAfterComposeObservable.notifyObservers(this);
  77106. // Handle size changes.
  77107. var size = this._mainTexture.getSize();
  77108. this.setMainTextureSize();
  77109. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77110. // Recreate RTT and post processes on size change.
  77111. this.onSizeChangedObservable.notifyObservers(this);
  77112. this.disposeTextureAndPostProcesses();
  77113. this.createTextureAndPostProcesses();
  77114. }
  77115. };
  77116. /**
  77117. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77118. * @param mesh The mesh to exclude from the highlight layer
  77119. */
  77120. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77121. if (!this._excludedMeshes) {
  77122. return;
  77123. }
  77124. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77125. if (!meshExcluded) {
  77126. this._excludedMeshes[mesh.uniqueId] = {
  77127. mesh: mesh,
  77128. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77129. mesh.getEngine().setStencilBuffer(false);
  77130. }),
  77131. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77132. mesh.getEngine().setStencilBuffer(true);
  77133. }),
  77134. };
  77135. }
  77136. };
  77137. /**
  77138. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77139. * @param mesh The mesh to highlight
  77140. */
  77141. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77142. if (!this._excludedMeshes) {
  77143. return;
  77144. }
  77145. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77146. if (meshExcluded) {
  77147. if (meshExcluded.beforeRender) {
  77148. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77149. }
  77150. if (meshExcluded.afterRender) {
  77151. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77152. }
  77153. }
  77154. this._excludedMeshes[mesh.uniqueId] = null;
  77155. };
  77156. /**
  77157. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77158. * @param mesh mesh to test
  77159. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77160. */
  77161. HighlightLayer.prototype.hasMesh = function (mesh) {
  77162. if (!this._meshes) {
  77163. return false;
  77164. }
  77165. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77166. };
  77167. /**
  77168. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77169. * @param mesh The mesh to highlight
  77170. * @param color The color of the highlight
  77171. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77172. */
  77173. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77174. var _this = this;
  77175. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77176. if (!this._meshes) {
  77177. return;
  77178. }
  77179. var meshHighlight = this._meshes[mesh.uniqueId];
  77180. if (meshHighlight) {
  77181. meshHighlight.color = color;
  77182. }
  77183. else {
  77184. this._meshes[mesh.uniqueId] = {
  77185. mesh: mesh,
  77186. color: color,
  77187. // Lambda required for capture due to Observable this context
  77188. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77189. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77190. _this.defaultStencilReference(mesh);
  77191. }
  77192. else {
  77193. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77194. }
  77195. }),
  77196. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77197. glowEmissiveOnly: glowEmissiveOnly
  77198. };
  77199. }
  77200. this._shouldRender = true;
  77201. };
  77202. /**
  77203. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77204. * @param mesh The mesh to highlight
  77205. */
  77206. HighlightLayer.prototype.removeMesh = function (mesh) {
  77207. if (!this._meshes) {
  77208. return;
  77209. }
  77210. var meshHighlight = this._meshes[mesh.uniqueId];
  77211. if (meshHighlight) {
  77212. if (meshHighlight.observerHighlight) {
  77213. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77214. }
  77215. if (meshHighlight.observerDefault) {
  77216. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77217. }
  77218. delete this._meshes[mesh.uniqueId];
  77219. }
  77220. this._shouldRender = false;
  77221. for (var meshHighlightToCheck in this._meshes) {
  77222. if (this._meshes[meshHighlightToCheck]) {
  77223. this._shouldRender = true;
  77224. break;
  77225. }
  77226. }
  77227. };
  77228. /**
  77229. * Returns true if the layer contains information to display, otherwise false.
  77230. */
  77231. HighlightLayer.prototype.shouldRender = function () {
  77232. return this.isEnabled && this._shouldRender;
  77233. };
  77234. /**
  77235. * Sets the main texture desired size which is the closest power of two
  77236. * of the engine canvas size.
  77237. */
  77238. HighlightLayer.prototype.setMainTextureSize = function () {
  77239. if (this._options.mainTextureFixedSize) {
  77240. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77241. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77242. }
  77243. else {
  77244. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77245. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77246. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77247. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77248. }
  77249. };
  77250. /**
  77251. * Force the stencil to the normal expected value for none glowing parts
  77252. */
  77253. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77254. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77255. };
  77256. /**
  77257. * Dispose only the render target textures and post process.
  77258. */
  77259. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77260. this._blurTexture.dispose();
  77261. this._mainTexture.dispose();
  77262. this._downSamplePostprocess.dispose();
  77263. this._horizontalBlurPostprocess.dispose();
  77264. this._verticalBlurPostprocess.dispose();
  77265. };
  77266. /**
  77267. * Dispose the highlight layer and free resources.
  77268. */
  77269. HighlightLayer.prototype.dispose = function () {
  77270. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77271. if (vertexBuffer) {
  77272. vertexBuffer.dispose();
  77273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77274. }
  77275. if (this._indexBuffer) {
  77276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77277. this._indexBuffer = null;
  77278. }
  77279. // Clean textures and post processes
  77280. this.disposeTextureAndPostProcesses();
  77281. if (this._meshes) {
  77282. // Clean mesh references
  77283. for (var id in this._meshes) {
  77284. var meshHighlight = this._meshes[id];
  77285. if (meshHighlight && meshHighlight.mesh) {
  77286. if (meshHighlight.observerHighlight) {
  77287. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77288. }
  77289. if (meshHighlight.observerDefault) {
  77290. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77291. }
  77292. }
  77293. }
  77294. this._meshes = null;
  77295. }
  77296. if (this._excludedMeshes) {
  77297. for (var id in this._excludedMeshes) {
  77298. var meshHighlight = this._excludedMeshes[id];
  77299. if (meshHighlight) {
  77300. if (meshHighlight.beforeRender) {
  77301. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77302. }
  77303. if (meshHighlight.afterRender) {
  77304. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77305. }
  77306. }
  77307. }
  77308. this._excludedMeshes = null;
  77309. }
  77310. // Remove from scene
  77311. var index = this._scene.highlightLayers.indexOf(this, 0);
  77312. if (index > -1) {
  77313. this._scene.highlightLayers.splice(index, 1);
  77314. }
  77315. // Callback
  77316. this.onDisposeObservable.notifyObservers(this);
  77317. this.onDisposeObservable.clear();
  77318. this.onBeforeRenderMainTextureObservable.clear();
  77319. this.onBeforeBlurObservable.clear();
  77320. this.onBeforeComposeObservable.clear();
  77321. this.onAfterComposeObservable.clear();
  77322. this.onSizeChangedObservable.clear();
  77323. };
  77324. /**
  77325. * The neutral color used during the preparation of the glow effect.
  77326. * This is black by default as the blend operation is a blend operation.
  77327. */
  77328. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77329. /**
  77330. * Stencil value used for glowing meshes.
  77331. */
  77332. HighlightLayer.glowingMeshStencilReference = 0x02;
  77333. /**
  77334. * Stencil value used for the other meshes in the scene.
  77335. */
  77336. HighlightLayer.normalMeshStencilReference = 0x01;
  77337. return HighlightLayer;
  77338. }());
  77339. BABYLON.HighlightLayer = HighlightLayer;
  77340. })(BABYLON || (BABYLON = {}));
  77341. //# sourceMappingURL=babylon.highlightlayer.js.map
  77342. var BABYLON;
  77343. (function (BABYLON) {
  77344. var AssetTaskState;
  77345. (function (AssetTaskState) {
  77346. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77347. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77348. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77349. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77350. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77351. var AbstractAssetTask = /** @class */ (function () {
  77352. function AbstractAssetTask(name) {
  77353. this.name = name;
  77354. this.isCompleted = false;
  77355. this.taskState = AssetTaskState.INIT;
  77356. }
  77357. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77358. var _this = this;
  77359. this.taskState = AssetTaskState.RUNNING;
  77360. this.runTask(scene, function () {
  77361. _this.onDoneCallback(onSuccess, onError);
  77362. }, function (msg, exception) {
  77363. _this.onErrorCallback(onError, msg, exception);
  77364. });
  77365. };
  77366. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77367. throw new Error("runTask is not implemented");
  77368. };
  77369. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77370. this.taskState = AssetTaskState.ERROR;
  77371. this.errorObject = {
  77372. message: message,
  77373. exception: exception
  77374. };
  77375. if (this.onError) {
  77376. this.onError(this, message, exception);
  77377. }
  77378. onError();
  77379. };
  77380. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77381. try {
  77382. this.taskState = AssetTaskState.DONE;
  77383. this.isCompleted = true;
  77384. if (this.onSuccess) {
  77385. this.onSuccess(this);
  77386. }
  77387. onSuccess();
  77388. }
  77389. catch (e) {
  77390. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77391. }
  77392. };
  77393. return AbstractAssetTask;
  77394. }());
  77395. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77396. var AssetsProgressEvent = /** @class */ (function () {
  77397. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77398. this.remainingCount = remainingCount;
  77399. this.totalCount = totalCount;
  77400. this.task = task;
  77401. }
  77402. return AssetsProgressEvent;
  77403. }());
  77404. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77405. var MeshAssetTask = /** @class */ (function (_super) {
  77406. __extends(MeshAssetTask, _super);
  77407. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  77408. var _this = _super.call(this, name) || this;
  77409. _this.name = name;
  77410. _this.meshesNames = meshesNames;
  77411. _this.rootUrl = rootUrl;
  77412. _this.sceneFilename = sceneFilename;
  77413. return _this;
  77414. }
  77415. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77416. var _this = this;
  77417. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77418. _this.loadedMeshes = meshes;
  77419. _this.loadedParticleSystems = particleSystems;
  77420. _this.loadedSkeletons = skeletons;
  77421. onSuccess();
  77422. }, null, function (scene, message, exception) {
  77423. onError(message, exception);
  77424. });
  77425. };
  77426. return MeshAssetTask;
  77427. }(AbstractAssetTask));
  77428. BABYLON.MeshAssetTask = MeshAssetTask;
  77429. var TextFileAssetTask = /** @class */ (function (_super) {
  77430. __extends(TextFileAssetTask, _super);
  77431. function TextFileAssetTask(name, url) {
  77432. var _this = _super.call(this, name) || this;
  77433. _this.name = name;
  77434. _this.url = url;
  77435. return _this;
  77436. }
  77437. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77438. var _this = this;
  77439. scene._loadFile(this.url, function (data) {
  77440. _this.text = data;
  77441. onSuccess();
  77442. }, undefined, false, true, function (request, exception) {
  77443. if (request) {
  77444. onError(request.status + " " + request.statusText, exception);
  77445. }
  77446. });
  77447. };
  77448. return TextFileAssetTask;
  77449. }(AbstractAssetTask));
  77450. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77451. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77452. __extends(BinaryFileAssetTask, _super);
  77453. function BinaryFileAssetTask(name, url) {
  77454. var _this = _super.call(this, name) || this;
  77455. _this.name = name;
  77456. _this.url = url;
  77457. return _this;
  77458. }
  77459. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77460. var _this = this;
  77461. scene._loadFile(this.url, function (data) {
  77462. _this.data = data;
  77463. onSuccess();
  77464. }, undefined, true, true, function (request, exception) {
  77465. if (request) {
  77466. onError(request.status + " " + request.statusText, exception);
  77467. }
  77468. });
  77469. };
  77470. return BinaryFileAssetTask;
  77471. }(AbstractAssetTask));
  77472. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77473. var ImageAssetTask = /** @class */ (function (_super) {
  77474. __extends(ImageAssetTask, _super);
  77475. function ImageAssetTask(name, url) {
  77476. var _this = _super.call(this, name) || this;
  77477. _this.name = name;
  77478. _this.url = url;
  77479. return _this;
  77480. }
  77481. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77482. var _this = this;
  77483. var img = new Image();
  77484. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77485. img.onload = function () {
  77486. _this.image = img;
  77487. onSuccess();
  77488. };
  77489. img.onerror = function (err) {
  77490. onError("Error loading image", err);
  77491. };
  77492. img.src = this.url;
  77493. };
  77494. return ImageAssetTask;
  77495. }(AbstractAssetTask));
  77496. BABYLON.ImageAssetTask = ImageAssetTask;
  77497. var TextureAssetTask = /** @class */ (function (_super) {
  77498. __extends(TextureAssetTask, _super);
  77499. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  77500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77501. var _this = _super.call(this, name) || this;
  77502. _this.name = name;
  77503. _this.url = url;
  77504. _this.noMipmap = noMipmap;
  77505. _this.invertY = invertY;
  77506. _this.samplingMode = samplingMode;
  77507. return _this;
  77508. }
  77509. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77510. var onload = function () {
  77511. onSuccess();
  77512. };
  77513. var onerror = function (message, exception) {
  77514. onError(message, exception);
  77515. };
  77516. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77517. };
  77518. return TextureAssetTask;
  77519. }(AbstractAssetTask));
  77520. BABYLON.TextureAssetTask = TextureAssetTask;
  77521. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77522. __extends(CubeTextureAssetTask, _super);
  77523. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  77524. var _this = _super.call(this, name) || this;
  77525. _this.name = name;
  77526. _this.url = url;
  77527. _this.extensions = extensions;
  77528. _this.noMipmap = noMipmap;
  77529. _this.files = files;
  77530. return _this;
  77531. }
  77532. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77533. var onload = function () {
  77534. onSuccess();
  77535. };
  77536. var onerror = function (message, exception) {
  77537. onError(message, exception);
  77538. };
  77539. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77540. };
  77541. return CubeTextureAssetTask;
  77542. }(AbstractAssetTask));
  77543. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77544. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77545. __extends(HDRCubeTextureAssetTask, _super);
  77546. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77547. if (noMipmap === void 0) { noMipmap = false; }
  77548. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77549. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77550. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77551. var _this = _super.call(this, name) || this;
  77552. _this.name = name;
  77553. _this.url = url;
  77554. _this.size = size;
  77555. _this.noMipmap = noMipmap;
  77556. _this.generateHarmonics = generateHarmonics;
  77557. _this.useInGammaSpace = useInGammaSpace;
  77558. _this.usePMREMGenerator = usePMREMGenerator;
  77559. return _this;
  77560. }
  77561. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77562. var onload = function () {
  77563. onSuccess();
  77564. };
  77565. var onerror = function (message, exception) {
  77566. onError(message, exception);
  77567. };
  77568. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77569. };
  77570. return HDRCubeTextureAssetTask;
  77571. }(AbstractAssetTask));
  77572. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77573. var AssetsManager = /** @class */ (function () {
  77574. function AssetsManager(scene) {
  77575. this._isLoading = false;
  77576. this.tasks = new Array();
  77577. this.waitingTasksCount = 0;
  77578. //Observables
  77579. this.onTaskSuccessObservable = new BABYLON.Observable();
  77580. this.onTaskErrorObservable = new BABYLON.Observable();
  77581. this.onTasksDoneObservable = new BABYLON.Observable();
  77582. this.onProgressObservable = new BABYLON.Observable();
  77583. this.useDefaultLoadingScreen = true;
  77584. this._scene = scene;
  77585. }
  77586. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77587. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77588. this.tasks.push(task);
  77589. return task;
  77590. };
  77591. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77592. var task = new TextFileAssetTask(taskName, url);
  77593. this.tasks.push(task);
  77594. return task;
  77595. };
  77596. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77597. var task = new BinaryFileAssetTask(taskName, url);
  77598. this.tasks.push(task);
  77599. return task;
  77600. };
  77601. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77602. var task = new ImageAssetTask(taskName, url);
  77603. this.tasks.push(task);
  77604. return task;
  77605. };
  77606. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77608. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77609. this.tasks.push(task);
  77610. return task;
  77611. };
  77612. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  77613. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  77614. this.tasks.push(task);
  77615. return task;
  77616. };
  77617. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77618. if (noMipmap === void 0) { noMipmap = false; }
  77619. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77620. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77621. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77622. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  77623. this.tasks.push(task);
  77624. return task;
  77625. };
  77626. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  77627. this.waitingTasksCount--;
  77628. try {
  77629. if (this.onProgress) {
  77630. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  77631. }
  77632. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  77633. }
  77634. catch (e) {
  77635. BABYLON.Tools.Error("Error running progress callbacks.");
  77636. console.log(e);
  77637. }
  77638. if (this.waitingTasksCount === 0) {
  77639. try {
  77640. if (this.onFinish) {
  77641. this.onFinish(this.tasks);
  77642. }
  77643. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77644. }
  77645. catch (e) {
  77646. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  77647. console.log(e);
  77648. }
  77649. this._isLoading = false;
  77650. this._scene.getEngine().hideLoadingUI();
  77651. }
  77652. };
  77653. AssetsManager.prototype._runTask = function (task) {
  77654. var _this = this;
  77655. var done = function () {
  77656. try {
  77657. if (_this.onTaskSuccess) {
  77658. _this.onTaskSuccess(task);
  77659. }
  77660. _this.onTaskSuccessObservable.notifyObservers(task);
  77661. _this._decreaseWaitingTasksCount(task);
  77662. }
  77663. catch (e) {
  77664. error("Error executing task success callbacks", e);
  77665. }
  77666. };
  77667. var error = function (message, exception) {
  77668. task.errorObject = task.errorObject || {
  77669. message: message,
  77670. exception: exception
  77671. };
  77672. if (_this.onTaskError) {
  77673. _this.onTaskError(task);
  77674. }
  77675. _this.onTaskErrorObservable.notifyObservers(task);
  77676. _this._decreaseWaitingTasksCount(task);
  77677. };
  77678. task.run(this._scene, done, error);
  77679. };
  77680. AssetsManager.prototype.reset = function () {
  77681. this._isLoading = false;
  77682. this.tasks = new Array();
  77683. return this;
  77684. };
  77685. AssetsManager.prototype.load = function () {
  77686. if (this._isLoading) {
  77687. return this;
  77688. }
  77689. this._isLoading = true;
  77690. this.waitingTasksCount = this.tasks.length;
  77691. if (this.waitingTasksCount === 0) {
  77692. if (this.onFinish) {
  77693. this.onFinish(this.tasks);
  77694. }
  77695. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77696. this._isLoading = false;
  77697. return this;
  77698. }
  77699. if (this.useDefaultLoadingScreen) {
  77700. this._scene.getEngine().displayLoadingUI();
  77701. }
  77702. for (var index = 0; index < this.tasks.length; index++) {
  77703. var task = this.tasks[index];
  77704. this._runTask(task);
  77705. }
  77706. return this;
  77707. };
  77708. return AssetsManager;
  77709. }());
  77710. BABYLON.AssetsManager = AssetsManager;
  77711. })(BABYLON || (BABYLON = {}));
  77712. //# sourceMappingURL=babylon.assetsManager.js.map
  77713. var BABYLON;
  77714. (function (BABYLON) {
  77715. var serializedGeometries = [];
  77716. var serializeGeometry = function (geometry, serializationGeometries) {
  77717. if (serializedGeometries[geometry.id]) {
  77718. return;
  77719. }
  77720. if (geometry.doNotSerialize) {
  77721. return;
  77722. }
  77723. if (geometry instanceof BABYLON.BoxGeometry) {
  77724. serializationGeometries.boxes.push(geometry.serialize());
  77725. }
  77726. else if (geometry instanceof BABYLON.SphereGeometry) {
  77727. serializationGeometries.spheres.push(geometry.serialize());
  77728. }
  77729. else if (geometry instanceof BABYLON.CylinderGeometry) {
  77730. serializationGeometries.cylinders.push(geometry.serialize());
  77731. }
  77732. else if (geometry instanceof BABYLON.TorusGeometry) {
  77733. serializationGeometries.toruses.push(geometry.serialize());
  77734. }
  77735. else if (geometry instanceof BABYLON.GroundGeometry) {
  77736. serializationGeometries.grounds.push(geometry.serialize());
  77737. }
  77738. else if (geometry instanceof BABYLON.Plane) {
  77739. serializationGeometries.planes.push(geometry.serialize());
  77740. }
  77741. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  77742. serializationGeometries.torusKnots.push(geometry.serialize());
  77743. }
  77744. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  77745. throw new Error("Unknown primitive type");
  77746. }
  77747. else {
  77748. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  77749. }
  77750. serializedGeometries[geometry.id] = true;
  77751. };
  77752. var serializeMesh = function (mesh, serializationScene) {
  77753. var serializationObject = {};
  77754. // Geometry
  77755. var geometry = mesh._geometry;
  77756. if (geometry) {
  77757. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  77758. // 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
  77759. serializeGeometry(geometry, serializationScene.geometries);
  77760. }
  77761. }
  77762. // Custom
  77763. if (mesh.serialize) {
  77764. mesh.serialize(serializationObject);
  77765. }
  77766. return serializationObject;
  77767. };
  77768. var finalizeSingleMesh = function (mesh, serializationObject) {
  77769. //only works if the mesh is already loaded
  77770. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77771. //serialize material
  77772. if (mesh.material) {
  77773. if (mesh.material instanceof BABYLON.StandardMaterial) {
  77774. serializationObject.materials = serializationObject.materials || [];
  77775. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77776. serializationObject.materials.push(mesh.material.serialize());
  77777. }
  77778. }
  77779. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  77780. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  77781. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77782. serializationObject.multiMaterials.push(mesh.material.serialize());
  77783. }
  77784. }
  77785. }
  77786. //serialize geometry
  77787. var geometry = mesh._geometry;
  77788. if (geometry) {
  77789. if (!serializationObject.geometries) {
  77790. serializationObject.geometries = {};
  77791. serializationObject.geometries.boxes = [];
  77792. serializationObject.geometries.spheres = [];
  77793. serializationObject.geometries.cylinders = [];
  77794. serializationObject.geometries.toruses = [];
  77795. serializationObject.geometries.grounds = [];
  77796. serializationObject.geometries.planes = [];
  77797. serializationObject.geometries.torusKnots = [];
  77798. serializationObject.geometries.vertexData = [];
  77799. }
  77800. serializeGeometry(geometry, serializationObject.geometries);
  77801. }
  77802. // Skeletons
  77803. if (mesh.skeleton) {
  77804. serializationObject.skeletons = serializationObject.skeletons || [];
  77805. serializationObject.skeletons.push(mesh.skeleton.serialize());
  77806. }
  77807. //serialize the actual mesh
  77808. serializationObject.meshes = serializationObject.meshes || [];
  77809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77810. }
  77811. };
  77812. var SceneSerializer = /** @class */ (function () {
  77813. function SceneSerializer() {
  77814. }
  77815. SceneSerializer.ClearCache = function () {
  77816. serializedGeometries = [];
  77817. };
  77818. SceneSerializer.Serialize = function (scene) {
  77819. var serializationObject = {};
  77820. SceneSerializer.ClearCache();
  77821. // Scene
  77822. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  77823. serializationObject.autoClear = scene.autoClear;
  77824. serializationObject.clearColor = scene.clearColor.asArray();
  77825. serializationObject.ambientColor = scene.ambientColor.asArray();
  77826. serializationObject.gravity = scene.gravity.asArray();
  77827. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  77828. serializationObject.workerCollisions = scene.workerCollisions;
  77829. // Fog
  77830. if (scene.fogMode && scene.fogMode !== 0) {
  77831. serializationObject.fogMode = scene.fogMode;
  77832. serializationObject.fogColor = scene.fogColor.asArray();
  77833. serializationObject.fogStart = scene.fogStart;
  77834. serializationObject.fogEnd = scene.fogEnd;
  77835. serializationObject.fogDensity = scene.fogDensity;
  77836. }
  77837. //Physics
  77838. if (scene.isPhysicsEnabled()) {
  77839. var physicEngine = scene.getPhysicsEngine();
  77840. if (physicEngine) {
  77841. serializationObject.physicsEnabled = true;
  77842. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  77843. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  77844. }
  77845. }
  77846. // Metadata
  77847. if (scene.metadata) {
  77848. serializationObject.metadata = scene.metadata;
  77849. }
  77850. // Morph targets
  77851. serializationObject.morphTargetManagers = [];
  77852. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  77853. var abstractMesh = _a[_i];
  77854. var manager = abstractMesh.morphTargetManager;
  77855. if (manager) {
  77856. serializationObject.morphTargetManagers.push(manager.serialize());
  77857. }
  77858. }
  77859. // Lights
  77860. serializationObject.lights = [];
  77861. var index;
  77862. var light;
  77863. for (index = 0; index < scene.lights.length; index++) {
  77864. light = scene.lights[index];
  77865. if (!light.doNotSerialize) {
  77866. serializationObject.lights.push(light.serialize());
  77867. }
  77868. }
  77869. // Cameras
  77870. serializationObject.cameras = [];
  77871. for (index = 0; index < scene.cameras.length; index++) {
  77872. var camera = scene.cameras[index];
  77873. if (!camera.doNotSerialize) {
  77874. serializationObject.cameras.push(camera.serialize());
  77875. }
  77876. }
  77877. if (scene.activeCamera) {
  77878. serializationObject.activeCameraID = scene.activeCamera.id;
  77879. }
  77880. // Animations
  77881. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  77882. // Materials
  77883. serializationObject.materials = [];
  77884. serializationObject.multiMaterials = [];
  77885. var material;
  77886. for (index = 0; index < scene.materials.length; index++) {
  77887. material = scene.materials[index];
  77888. if (!material.doNotSerialize) {
  77889. serializationObject.materials.push(material.serialize());
  77890. }
  77891. }
  77892. // MultiMaterials
  77893. serializationObject.multiMaterials = [];
  77894. for (index = 0; index < scene.multiMaterials.length; index++) {
  77895. var multiMaterial = scene.multiMaterials[index];
  77896. serializationObject.multiMaterials.push(multiMaterial.serialize());
  77897. }
  77898. // Environment texture
  77899. if (scene.environmentTexture) {
  77900. serializationObject.environmentTexture = scene.environmentTexture.name;
  77901. }
  77902. // Skeletons
  77903. serializationObject.skeletons = [];
  77904. for (index = 0; index < scene.skeletons.length; index++) {
  77905. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  77906. }
  77907. // Transform nodes
  77908. serializationObject.transformNodes = [];
  77909. for (index = 0; index < scene.transformNodes.length; index++) {
  77910. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  77911. }
  77912. // Geometries
  77913. serializationObject.geometries = {};
  77914. serializationObject.geometries.boxes = [];
  77915. serializationObject.geometries.spheres = [];
  77916. serializationObject.geometries.cylinders = [];
  77917. serializationObject.geometries.toruses = [];
  77918. serializationObject.geometries.grounds = [];
  77919. serializationObject.geometries.planes = [];
  77920. serializationObject.geometries.torusKnots = [];
  77921. serializationObject.geometries.vertexData = [];
  77922. serializedGeometries = [];
  77923. var geometries = scene.getGeometries();
  77924. for (index = 0; index < geometries.length; index++) {
  77925. var geometry = geometries[index];
  77926. if (geometry.isReady()) {
  77927. serializeGeometry(geometry, serializationObject.geometries);
  77928. }
  77929. }
  77930. // Meshes
  77931. serializationObject.meshes = [];
  77932. for (index = 0; index < scene.meshes.length; index++) {
  77933. var abstractMesh = scene.meshes[index];
  77934. if (abstractMesh instanceof BABYLON.Mesh) {
  77935. var mesh = abstractMesh;
  77936. if (!mesh.doNotSerialize) {
  77937. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77938. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77939. }
  77940. }
  77941. }
  77942. }
  77943. // Particles Systems
  77944. serializationObject.particleSystems = [];
  77945. for (index = 0; index < scene.particleSystems.length; index++) {
  77946. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  77947. }
  77948. // Lens flares
  77949. serializationObject.lensFlareSystems = [];
  77950. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  77951. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  77952. }
  77953. // Shadows
  77954. serializationObject.shadowGenerators = [];
  77955. for (index = 0; index < scene.lights.length; index++) {
  77956. light = scene.lights[index];
  77957. var shadowGenerator = light.getShadowGenerator();
  77958. if (shadowGenerator) {
  77959. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77960. }
  77961. }
  77962. // Action Manager
  77963. if (scene.actionManager) {
  77964. serializationObject.actions = scene.actionManager.serialize("scene");
  77965. }
  77966. // Audio
  77967. serializationObject.sounds = [];
  77968. for (index = 0; index < scene.soundTracks.length; index++) {
  77969. var soundtrack = scene.soundTracks[index];
  77970. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  77971. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  77972. }
  77973. }
  77974. return serializationObject;
  77975. };
  77976. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  77977. if (withParents === void 0) { withParents = false; }
  77978. if (withChildren === void 0) { withChildren = false; }
  77979. var serializationObject = {};
  77980. SceneSerializer.ClearCache();
  77981. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  77982. if (withParents || withChildren) {
  77983. //deliberate for loop! not for each, appended should be processed as well.
  77984. for (var i = 0; i < toSerialize.length; ++i) {
  77985. if (withChildren) {
  77986. toSerialize[i].getDescendants().forEach(function (node) {
  77987. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  77988. toSerialize.push(node);
  77989. }
  77990. });
  77991. }
  77992. //make sure the array doesn't contain the object already
  77993. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  77994. toSerialize.push(toSerialize[i].parent);
  77995. }
  77996. }
  77997. }
  77998. toSerialize.forEach(function (mesh) {
  77999. finalizeSingleMesh(mesh, serializationObject);
  78000. });
  78001. return serializationObject;
  78002. };
  78003. return SceneSerializer;
  78004. }());
  78005. BABYLON.SceneSerializer = SceneSerializer;
  78006. })(BABYLON || (BABYLON = {}));
  78007. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78008. var BABYLON;
  78009. (function (BABYLON) {
  78010. var ReflectionProbe = /** @class */ (function () {
  78011. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78012. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78013. var _this = this;
  78014. this.name = name;
  78015. this._viewMatrix = BABYLON.Matrix.Identity();
  78016. this._target = BABYLON.Vector3.Zero();
  78017. this._add = BABYLON.Vector3.Zero();
  78018. this.invertYAxis = false;
  78019. this.position = BABYLON.Vector3.Zero();
  78020. this._scene = scene;
  78021. this._scene.reflectionProbes.push(this);
  78022. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78023. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78024. switch (faceIndex) {
  78025. case 0:
  78026. _this._add.copyFromFloats(1, 0, 0);
  78027. break;
  78028. case 1:
  78029. _this._add.copyFromFloats(-1, 0, 0);
  78030. break;
  78031. case 2:
  78032. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78033. break;
  78034. case 3:
  78035. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78036. break;
  78037. case 4:
  78038. _this._add.copyFromFloats(0, 0, 1);
  78039. break;
  78040. case 5:
  78041. _this._add.copyFromFloats(0, 0, -1);
  78042. break;
  78043. }
  78044. if (_this._attachedMesh) {
  78045. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78046. }
  78047. _this.position.addToRef(_this._add, _this._target);
  78048. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78049. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78050. scene._forcedViewPosition = _this.position;
  78051. });
  78052. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78053. scene._forcedViewPosition = null;
  78054. scene.updateTransformMatrix(true);
  78055. });
  78056. if (scene.activeCamera) {
  78057. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78058. }
  78059. }
  78060. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78061. get: function () {
  78062. return this._renderTargetTexture.samples;
  78063. },
  78064. set: function (value) {
  78065. this._renderTargetTexture.samples = value;
  78066. },
  78067. enumerable: true,
  78068. configurable: true
  78069. });
  78070. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78071. get: function () {
  78072. return this._renderTargetTexture.refreshRate;
  78073. },
  78074. set: function (value) {
  78075. this._renderTargetTexture.refreshRate = value;
  78076. },
  78077. enumerable: true,
  78078. configurable: true
  78079. });
  78080. ReflectionProbe.prototype.getScene = function () {
  78081. return this._scene;
  78082. };
  78083. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78084. get: function () {
  78085. return this._renderTargetTexture;
  78086. },
  78087. enumerable: true,
  78088. configurable: true
  78089. });
  78090. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78091. get: function () {
  78092. return this._renderTargetTexture.renderList;
  78093. },
  78094. enumerable: true,
  78095. configurable: true
  78096. });
  78097. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78098. this._attachedMesh = mesh;
  78099. };
  78100. /**
  78101. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78102. *
  78103. * @param renderingGroupId The rendering group id corresponding to its index
  78104. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78105. */
  78106. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78107. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78108. };
  78109. ReflectionProbe.prototype.dispose = function () {
  78110. var index = this._scene.reflectionProbes.indexOf(this);
  78111. if (index !== -1) {
  78112. // Remove from the scene if found
  78113. this._scene.reflectionProbes.splice(index, 1);
  78114. }
  78115. if (this._renderTargetTexture) {
  78116. this._renderTargetTexture.dispose();
  78117. this._renderTargetTexture = null;
  78118. }
  78119. };
  78120. return ReflectionProbe;
  78121. }());
  78122. BABYLON.ReflectionProbe = ReflectionProbe;
  78123. })(BABYLON || (BABYLON = {}));
  78124. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78125. var BABYLON;
  78126. (function (BABYLON) {
  78127. var Layer = /** @class */ (function () {
  78128. function Layer(name, imgUrl, scene, isBackground, color) {
  78129. this.name = name;
  78130. this.scale = new BABYLON.Vector2(1, 1);
  78131. this.offset = new BABYLON.Vector2(0, 0);
  78132. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78133. this.layerMask = 0x0FFFFFFF;
  78134. this._vertexBuffers = {};
  78135. // Events
  78136. /**
  78137. * An event triggered when the layer is disposed.
  78138. * @type {BABYLON.Observable}
  78139. */
  78140. this.onDisposeObservable = new BABYLON.Observable();
  78141. /**
  78142. * An event triggered before rendering the scene
  78143. * @type {BABYLON.Observable}
  78144. */
  78145. this.onBeforeRenderObservable = new BABYLON.Observable();
  78146. /**
  78147. * An event triggered after rendering the scene
  78148. * @type {BABYLON.Observable}
  78149. */
  78150. this.onAfterRenderObservable = new BABYLON.Observable();
  78151. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78152. this.isBackground = isBackground === undefined ? true : isBackground;
  78153. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78154. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78155. this._scene.layers.push(this);
  78156. var engine = this._scene.getEngine();
  78157. // VBO
  78158. var vertices = [];
  78159. vertices.push(1, 1);
  78160. vertices.push(-1, 1);
  78161. vertices.push(-1, -1);
  78162. vertices.push(1, -1);
  78163. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78164. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78165. this._createIndexBuffer();
  78166. // Effects
  78167. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78168. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78169. }
  78170. Object.defineProperty(Layer.prototype, "onDispose", {
  78171. set: function (callback) {
  78172. if (this._onDisposeObserver) {
  78173. this.onDisposeObservable.remove(this._onDisposeObserver);
  78174. }
  78175. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78176. },
  78177. enumerable: true,
  78178. configurable: true
  78179. });
  78180. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78181. set: function (callback) {
  78182. if (this._onBeforeRenderObserver) {
  78183. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78184. }
  78185. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78186. },
  78187. enumerable: true,
  78188. configurable: true
  78189. });
  78190. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78191. set: function (callback) {
  78192. if (this._onAfterRenderObserver) {
  78193. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78194. }
  78195. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78196. },
  78197. enumerable: true,
  78198. configurable: true
  78199. });
  78200. Layer.prototype._createIndexBuffer = function () {
  78201. var engine = this._scene.getEngine();
  78202. // Indices
  78203. var indices = [];
  78204. indices.push(0);
  78205. indices.push(1);
  78206. indices.push(2);
  78207. indices.push(0);
  78208. indices.push(2);
  78209. indices.push(3);
  78210. this._indexBuffer = engine.createIndexBuffer(indices);
  78211. };
  78212. Layer.prototype._rebuild = function () {
  78213. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78214. if (vb) {
  78215. vb._rebuild();
  78216. }
  78217. this._createIndexBuffer();
  78218. };
  78219. Layer.prototype.render = function () {
  78220. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78221. // Check
  78222. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78223. return;
  78224. var engine = this._scene.getEngine();
  78225. this.onBeforeRenderObservable.notifyObservers(this);
  78226. // Render
  78227. engine.enableEffect(currentEffect);
  78228. engine.setState(false);
  78229. // Texture
  78230. currentEffect.setTexture("textureSampler", this.texture);
  78231. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78232. // Color
  78233. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78234. // Scale / offset
  78235. currentEffect.setVector2("offset", this.offset);
  78236. currentEffect.setVector2("scale", this.scale);
  78237. // VBOs
  78238. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78239. // Draw order
  78240. if (!this.alphaTest) {
  78241. engine.setAlphaMode(this.alphaBlendingMode);
  78242. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78243. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78244. }
  78245. else {
  78246. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78247. }
  78248. this.onAfterRenderObservable.notifyObservers(this);
  78249. };
  78250. Layer.prototype.dispose = function () {
  78251. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78252. if (vertexBuffer) {
  78253. vertexBuffer.dispose();
  78254. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78255. }
  78256. if (this._indexBuffer) {
  78257. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78258. this._indexBuffer = null;
  78259. }
  78260. if (this.texture) {
  78261. this.texture.dispose();
  78262. this.texture = null;
  78263. }
  78264. // Remove from scene
  78265. var index = this._scene.layers.indexOf(this);
  78266. this._scene.layers.splice(index, 1);
  78267. // Callback
  78268. this.onDisposeObservable.notifyObservers(this);
  78269. this.onDisposeObservable.clear();
  78270. this.onAfterRenderObservable.clear();
  78271. this.onBeforeRenderObservable.clear();
  78272. };
  78273. return Layer;
  78274. }());
  78275. BABYLON.Layer = Layer;
  78276. })(BABYLON || (BABYLON = {}));
  78277. //# sourceMappingURL=babylon.layer.js.map
  78278. var BABYLON;
  78279. (function (BABYLON) {
  78280. var TextureTools = /** @class */ (function () {
  78281. function TextureTools() {
  78282. }
  78283. /**
  78284. * Uses the GPU to create a copy texture rescaled at a given size
  78285. * @param texture Texture to copy from
  78286. * @param width Desired width
  78287. * @param height Desired height
  78288. * @return Generated texture
  78289. */
  78290. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78291. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78292. var scene = texture.getScene();
  78293. var engine = scene.getEngine();
  78294. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78295. rtt.wrapU = texture.wrapU;
  78296. rtt.wrapV = texture.wrapV;
  78297. rtt.uOffset = texture.uOffset;
  78298. rtt.vOffset = texture.vOffset;
  78299. rtt.uScale = texture.uScale;
  78300. rtt.vScale = texture.vScale;
  78301. rtt.uAng = texture.uAng;
  78302. rtt.vAng = texture.vAng;
  78303. rtt.wAng = texture.wAng;
  78304. rtt.coordinatesIndex = texture.coordinatesIndex;
  78305. rtt.level = texture.level;
  78306. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78307. rtt._texture.isReady = false;
  78308. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78309. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78310. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78311. passPostProcess.getEffect().executeWhenCompiled(function () {
  78312. passPostProcess.onApply = function (effect) {
  78313. effect.setTexture("textureSampler", texture);
  78314. };
  78315. var internalTexture = rtt.getInternalTexture();
  78316. if (internalTexture) {
  78317. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78318. engine.unBindFramebuffer(internalTexture);
  78319. rtt.disposeFramebufferObjects();
  78320. passPostProcess.dispose();
  78321. internalTexture.isReady = true;
  78322. }
  78323. });
  78324. return rtt;
  78325. };
  78326. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78327. if (!scene._environmentBRDFTexture) {
  78328. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78329. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78330. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78331. scene._environmentBRDFTexture = texture;
  78332. }
  78333. return scene._environmentBRDFTexture;
  78334. };
  78335. 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=";
  78336. return TextureTools;
  78337. }());
  78338. BABYLON.TextureTools = TextureTools;
  78339. })(BABYLON || (BABYLON = {}));
  78340. //# sourceMappingURL=babylon.textureTools.js.map
  78341. var BABYLON;
  78342. (function (BABYLON) {
  78343. var FramingBehavior = /** @class */ (function () {
  78344. function FramingBehavior() {
  78345. this._mode = FramingBehavior.FitFrustumSidesMode;
  78346. this._radiusScale = 1.0;
  78347. this._positionScale = 0.5;
  78348. this._defaultElevation = 0.3;
  78349. this._elevationReturnTime = 1500;
  78350. this._elevationReturnWaitTime = 1000;
  78351. this._zoomStopsAnimation = false;
  78352. this._framingTime = 1500;
  78353. this._isPointerDown = false;
  78354. this._lastInteractionTime = -Infinity;
  78355. // Framing control
  78356. this._animatables = new Array();
  78357. this._betaIsAnimating = false;
  78358. }
  78359. Object.defineProperty(FramingBehavior.prototype, "name", {
  78360. get: function () {
  78361. return "Framing";
  78362. },
  78363. enumerable: true,
  78364. configurable: true
  78365. });
  78366. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78367. /**
  78368. * Gets current mode used by the behavior.
  78369. */
  78370. get: function () {
  78371. return this._mode;
  78372. },
  78373. /**
  78374. * Sets the current mode used by the behavior
  78375. */
  78376. set: function (mode) {
  78377. this._mode = mode;
  78378. },
  78379. enumerable: true,
  78380. configurable: true
  78381. });
  78382. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78383. /**
  78384. * Gets the scale applied to the radius
  78385. */
  78386. get: function () {
  78387. return this._radiusScale;
  78388. },
  78389. /**
  78390. * Sets the scale applied to the radius (1 by default)
  78391. */
  78392. set: function (radius) {
  78393. this._radiusScale = radius;
  78394. },
  78395. enumerable: true,
  78396. configurable: true
  78397. });
  78398. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78399. /**
  78400. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78401. */
  78402. get: function () {
  78403. return this._positionScale;
  78404. },
  78405. /**
  78406. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78407. */
  78408. set: function (scale) {
  78409. this._positionScale = scale;
  78410. },
  78411. enumerable: true,
  78412. configurable: true
  78413. });
  78414. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78415. /**
  78416. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78417. * behaviour is triggered, in radians.
  78418. */
  78419. get: function () {
  78420. return this._defaultElevation;
  78421. },
  78422. /**
  78423. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78424. * behaviour is triggered, in radians.
  78425. */
  78426. set: function (elevation) {
  78427. this._defaultElevation = elevation;
  78428. },
  78429. enumerable: true,
  78430. configurable: true
  78431. });
  78432. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78433. /**
  78434. * Gets the time (in milliseconds) taken to return to the default beta position.
  78435. * Negative value indicates camera should not return to default.
  78436. */
  78437. get: function () {
  78438. return this._elevationReturnTime;
  78439. },
  78440. /**
  78441. * Sets the time (in milliseconds) taken to return to the default beta position.
  78442. * Negative value indicates camera should not return to default.
  78443. */
  78444. set: function (speed) {
  78445. this._elevationReturnTime = speed;
  78446. },
  78447. enumerable: true,
  78448. configurable: true
  78449. });
  78450. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78451. /**
  78452. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78453. */
  78454. get: function () {
  78455. return this._elevationReturnWaitTime;
  78456. },
  78457. /**
  78458. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78459. */
  78460. set: function (time) {
  78461. this._elevationReturnWaitTime = time;
  78462. },
  78463. enumerable: true,
  78464. configurable: true
  78465. });
  78466. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78467. /**
  78468. * Gets the flag that indicates if user zooming should stop animation.
  78469. */
  78470. get: function () {
  78471. return this._zoomStopsAnimation;
  78472. },
  78473. /**
  78474. * Sets the flag that indicates if user zooming should stop animation.
  78475. */
  78476. set: function (flag) {
  78477. this._zoomStopsAnimation = flag;
  78478. },
  78479. enumerable: true,
  78480. configurable: true
  78481. });
  78482. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78483. /**
  78484. * Gets the transition time when framing the mesh, in milliseconds
  78485. */
  78486. get: function () {
  78487. return this._framingTime;
  78488. },
  78489. /**
  78490. * Sets the transition time when framing the mesh, in milliseconds
  78491. */
  78492. set: function (time) {
  78493. this._framingTime = time;
  78494. },
  78495. enumerable: true,
  78496. configurable: true
  78497. });
  78498. FramingBehavior.prototype.init = function () {
  78499. // Do notihng
  78500. };
  78501. FramingBehavior.prototype.attach = function (camera) {
  78502. var _this = this;
  78503. this._attachedCamera = camera;
  78504. var scene = this._attachedCamera.getScene();
  78505. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78506. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78507. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78508. _this._isPointerDown = true;
  78509. return;
  78510. }
  78511. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78512. _this._isPointerDown = false;
  78513. }
  78514. });
  78515. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78516. if (mesh) {
  78517. _this.zoomOnMesh(mesh);
  78518. }
  78519. });
  78520. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78521. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78522. _this._applyUserInteraction();
  78523. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78524. // back to the default position after a given timeout
  78525. _this._maintainCameraAboveGround();
  78526. });
  78527. };
  78528. FramingBehavior.prototype.detach = function () {
  78529. if (!this._attachedCamera) {
  78530. return;
  78531. }
  78532. var scene = this._attachedCamera.getScene();
  78533. if (this._onPrePointerObservableObserver) {
  78534. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78535. }
  78536. if (this._onAfterCheckInputsObserver) {
  78537. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78538. }
  78539. if (this._onMeshTargetChangedObserver) {
  78540. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78541. }
  78542. this._attachedCamera = null;
  78543. };
  78544. /**
  78545. * Targets the given mesh and updates zoom level accordingly.
  78546. * @param mesh The mesh to target.
  78547. * @param radius Optional. If a cached radius position already exists, overrides default.
  78548. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78549. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78550. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78551. */
  78552. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78553. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78554. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78555. mesh.computeWorldMatrix(true);
  78556. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78557. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78558. };
  78559. /**
  78560. * Targets the given mesh with its children and updates zoom level accordingly.
  78561. * @param mesh The mesh to target.
  78562. * @param radius Optional. If a cached radius position already exists, overrides default.
  78563. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78564. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78565. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78566. */
  78567. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78568. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78569. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78570. mesh.computeWorldMatrix(true);
  78571. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  78572. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  78573. };
  78574. /**
  78575. * Targets the given meshes with their children and updates zoom level accordingly.
  78576. * @param meshes The mesh to target.
  78577. * @param radius Optional. If a cached radius position already exists, overrides default.
  78578. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78579. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78580. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78581. */
  78582. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  78583. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78584. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78585. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  78586. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  78587. for (var i = 0; i < meshes.length; i++) {
  78588. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  78589. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  78590. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  78591. }
  78592. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  78593. };
  78594. /**
  78595. * Targets the given mesh and updates zoom level accordingly.
  78596. * @param mesh The mesh to target.
  78597. * @param radius Optional. If a cached radius position already exists, overrides default.
  78598. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78599. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78600. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78601. */
  78602. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  78603. var _this = this;
  78604. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78605. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78606. var zoomTarget;
  78607. if (!this._attachedCamera) {
  78608. return;
  78609. }
  78610. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  78611. var bottom = minimumWorld.y;
  78612. var top = maximumWorld.y;
  78613. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  78614. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  78615. if (focusOnOriginXZ) {
  78616. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  78617. }
  78618. else {
  78619. var centerWorld = minimumWorld.add(radiusWorld);
  78620. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  78621. }
  78622. if (!this._vectorTransition) {
  78623. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  78624. }
  78625. this._betaIsAnimating = true;
  78626. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  78627. if (animatable) {
  78628. this._animatables.push(animatable);
  78629. }
  78630. // sets the radius and lower radius bounds
  78631. // Small delta ensures camera is not always at lower zoom limit.
  78632. var radius = 0;
  78633. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  78634. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78635. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  78636. radius = position;
  78637. }
  78638. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78639. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78640. if (this._attachedCamera.lowerRadiusLimit === null) {
  78641. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  78642. }
  78643. }
  78644. // Set sensibilities
  78645. var extend = maximumWorld.subtract(minimumWorld).length();
  78646. this._attachedCamera.panningSensibility = 5000 / extend;
  78647. this._attachedCamera.wheelPrecision = 100 / radius;
  78648. // transition to new radius
  78649. if (!this._radiusTransition) {
  78650. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78651. }
  78652. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  78653. if (onAnimationEnd) {
  78654. onAnimationEnd();
  78655. }
  78656. if (_this._attachedCamera) {
  78657. _this._attachedCamera.storeState();
  78658. }
  78659. });
  78660. if (animatable) {
  78661. this._animatables.push(animatable);
  78662. }
  78663. };
  78664. /**
  78665. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  78666. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  78667. * frustum width.
  78668. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  78669. * to fully enclose the mesh in the viewing frustum.
  78670. */
  78671. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  78672. var size = maximumWorld.subtract(minimumWorld);
  78673. var boxVectorGlobalDiagonal = size.length();
  78674. var frustumSlope = this._getFrustumSlope();
  78675. // Formula for setting distance
  78676. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  78677. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  78678. // Horizon distance
  78679. var radius = radiusWithoutFraming * this._radiusScale;
  78680. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  78681. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  78682. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  78683. var camera = this._attachedCamera;
  78684. if (!camera) {
  78685. return 0;
  78686. }
  78687. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78688. // Don't exceed the requested limit
  78689. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  78690. }
  78691. // Don't exceed the upper radius limit
  78692. if (camera.upperRadiusLimit) {
  78693. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  78694. }
  78695. return distance;
  78696. };
  78697. /**
  78698. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  78699. * is automatically returned to its default position (expected to be above ground plane).
  78700. */
  78701. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  78702. var _this = this;
  78703. if (this._elevationReturnTime < 0) {
  78704. return;
  78705. }
  78706. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  78707. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  78708. var limitBeta = Math.PI * 0.5;
  78709. // Bring the camera back up if below the ground plane
  78710. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  78711. this._betaIsAnimating = true;
  78712. //Transition to new position
  78713. this.stopAllAnimations();
  78714. if (!this._betaTransition) {
  78715. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78716. }
  78717. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  78718. _this._clearAnimationLocks();
  78719. _this.stopAllAnimations();
  78720. });
  78721. if (animatabe) {
  78722. this._animatables.push(animatabe);
  78723. }
  78724. }
  78725. };
  78726. /**
  78727. * Returns the frustum slope based on the canvas ratio and camera FOV
  78728. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  78729. */
  78730. FramingBehavior.prototype._getFrustumSlope = function () {
  78731. // Calculate the viewport ratio
  78732. // Aspect Ratio is Height/Width.
  78733. var camera = this._attachedCamera;
  78734. if (!camera) {
  78735. return BABYLON.Vector2.Zero();
  78736. }
  78737. var engine = camera.getScene().getEngine();
  78738. var aspectRatio = engine.getAspectRatio(camera);
  78739. // Camera FOV is the vertical field of view (top-bottom) in radians.
  78740. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  78741. var frustumSlopeY = Math.tan(camera.fov / 2);
  78742. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  78743. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  78744. // along the forward vector.
  78745. var frustumSlopeX = frustumSlopeY * aspectRatio;
  78746. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  78747. };
  78748. /**
  78749. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  78750. */
  78751. FramingBehavior.prototype._clearAnimationLocks = function () {
  78752. this._betaIsAnimating = false;
  78753. };
  78754. /**
  78755. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78756. */
  78757. FramingBehavior.prototype._applyUserInteraction = function () {
  78758. if (this.isUserIsMoving) {
  78759. this._lastInteractionTime = BABYLON.Tools.Now;
  78760. this.stopAllAnimations();
  78761. this._clearAnimationLocks();
  78762. }
  78763. };
  78764. /**
  78765. * Stops and removes all animations that have been applied to the camera
  78766. */
  78767. FramingBehavior.prototype.stopAllAnimations = function () {
  78768. if (this._attachedCamera) {
  78769. this._attachedCamera.animations = [];
  78770. }
  78771. while (this._animatables.length) {
  78772. if (this._animatables[0]) {
  78773. this._animatables[0].onAnimationEnd = null;
  78774. this._animatables[0].stop();
  78775. }
  78776. this._animatables.shift();
  78777. }
  78778. };
  78779. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  78780. /**
  78781. * Gets a value indicating if the user is moving the camera
  78782. */
  78783. get: function () {
  78784. if (!this._attachedCamera) {
  78785. return false;
  78786. }
  78787. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  78788. this._attachedCamera.inertialBetaOffset !== 0 ||
  78789. this._attachedCamera.inertialRadiusOffset !== 0 ||
  78790. this._attachedCamera.inertialPanningX !== 0 ||
  78791. this._attachedCamera.inertialPanningY !== 0 ||
  78792. this._isPointerDown;
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. /**
  78798. * The easing function used by animations
  78799. */
  78800. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  78801. /**
  78802. * The easing mode used by animations
  78803. */
  78804. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  78805. // Statics
  78806. /**
  78807. * The camera can move all the way towards the mesh.
  78808. */
  78809. FramingBehavior.IgnoreBoundsSizeMode = 0;
  78810. /**
  78811. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  78812. */
  78813. FramingBehavior.FitFrustumSidesMode = 1;
  78814. return FramingBehavior;
  78815. }());
  78816. BABYLON.FramingBehavior = FramingBehavior;
  78817. })(BABYLON || (BABYLON = {}));
  78818. //# sourceMappingURL=babylon.framingBehavior.js.map
  78819. var BABYLON;
  78820. (function (BABYLON) {
  78821. /**
  78822. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  78823. */
  78824. var BouncingBehavior = /** @class */ (function () {
  78825. function BouncingBehavior() {
  78826. /**
  78827. * The duration of the animation, in milliseconds
  78828. */
  78829. this.transitionDuration = 450;
  78830. /**
  78831. * Length of the distance animated by the transition when lower radius is reached
  78832. */
  78833. this.lowerRadiusTransitionRange = 2;
  78834. /**
  78835. * Length of the distance animated by the transition when upper radius is reached
  78836. */
  78837. this.upperRadiusTransitionRange = -2;
  78838. this._autoTransitionRange = false;
  78839. // Animations
  78840. this._radiusIsAnimating = false;
  78841. this._radiusBounceTransition = null;
  78842. this._animatables = new Array();
  78843. }
  78844. Object.defineProperty(BouncingBehavior.prototype, "name", {
  78845. get: function () {
  78846. return "Bouncing";
  78847. },
  78848. enumerable: true,
  78849. configurable: true
  78850. });
  78851. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  78852. /**
  78853. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78854. */
  78855. get: function () {
  78856. return this._autoTransitionRange;
  78857. },
  78858. /**
  78859. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78860. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  78861. */
  78862. set: function (value) {
  78863. var _this = this;
  78864. if (this._autoTransitionRange === value) {
  78865. return;
  78866. }
  78867. this._autoTransitionRange = value;
  78868. var camera = this._attachedCamera;
  78869. if (!camera) {
  78870. return;
  78871. }
  78872. if (value) {
  78873. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78874. if (!mesh) {
  78875. return;
  78876. }
  78877. mesh.computeWorldMatrix(true);
  78878. var diagonal = mesh.getBoundingInfo().diagonalLength;
  78879. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  78880. _this.upperRadiusTransitionRange = diagonal * 0.05;
  78881. });
  78882. }
  78883. else if (this._onMeshTargetChangedObserver) {
  78884. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78885. }
  78886. },
  78887. enumerable: true,
  78888. configurable: true
  78889. });
  78890. BouncingBehavior.prototype.init = function () {
  78891. // Do notihng
  78892. };
  78893. BouncingBehavior.prototype.attach = function (camera) {
  78894. var _this = this;
  78895. this._attachedCamera = camera;
  78896. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78897. if (!_this._attachedCamera) {
  78898. return;
  78899. }
  78900. // Add the bounce animation to the lower radius limit
  78901. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  78902. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  78903. }
  78904. // Add the bounce animation to the upper radius limit
  78905. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  78906. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  78907. }
  78908. });
  78909. };
  78910. BouncingBehavior.prototype.detach = function () {
  78911. if (!this._attachedCamera) {
  78912. return;
  78913. }
  78914. if (this._onAfterCheckInputsObserver) {
  78915. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78916. }
  78917. if (this._onMeshTargetChangedObserver) {
  78918. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78919. }
  78920. this._attachedCamera = null;
  78921. };
  78922. /**
  78923. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  78924. * @param radiusLimit The limit to check against.
  78925. * @return Bool to indicate if at limit.
  78926. */
  78927. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  78928. if (!this._attachedCamera) {
  78929. return false;
  78930. }
  78931. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  78932. return true;
  78933. }
  78934. return false;
  78935. };
  78936. /**
  78937. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  78938. * @param radiusDelta The delta by which to animate to. Can be negative.
  78939. */
  78940. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  78941. var _this = this;
  78942. if (!this._attachedCamera) {
  78943. return;
  78944. }
  78945. if (!this._radiusBounceTransition) {
  78946. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  78947. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  78948. }
  78949. // Prevent zoom until bounce has completed
  78950. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  78951. this._attachedCamera.wheelPrecision = Infinity;
  78952. this._attachedCamera.inertialRadiusOffset = 0;
  78953. // Animate to the radius limit
  78954. this.stopAllAnimations();
  78955. this._radiusIsAnimating = true;
  78956. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  78957. if (animatable) {
  78958. this._animatables.push(animatable);
  78959. }
  78960. };
  78961. /**
  78962. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  78963. */
  78964. BouncingBehavior.prototype._clearAnimationLocks = function () {
  78965. this._radiusIsAnimating = false;
  78966. if (this._attachedCamera) {
  78967. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  78968. }
  78969. };
  78970. /**
  78971. * Stops and removes all animations that have been applied to the camera
  78972. */
  78973. BouncingBehavior.prototype.stopAllAnimations = function () {
  78974. if (this._attachedCamera) {
  78975. this._attachedCamera.animations = [];
  78976. }
  78977. while (this._animatables.length) {
  78978. this._animatables[0].onAnimationEnd = null;
  78979. this._animatables[0].stop();
  78980. this._animatables.shift();
  78981. }
  78982. };
  78983. /**
  78984. * The easing function used by animations
  78985. */
  78986. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  78987. /**
  78988. * The easing mode used by animations
  78989. */
  78990. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  78991. return BouncingBehavior;
  78992. }());
  78993. BABYLON.BouncingBehavior = BouncingBehavior;
  78994. })(BABYLON || (BABYLON = {}));
  78995. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  78996. var BABYLON;
  78997. (function (BABYLON) {
  78998. var AutoRotationBehavior = /** @class */ (function () {
  78999. function AutoRotationBehavior() {
  79000. this._zoomStopsAnimation = false;
  79001. this._idleRotationSpeed = 0.05;
  79002. this._idleRotationWaitTime = 2000;
  79003. this._idleRotationSpinupTime = 2000;
  79004. this._isPointerDown = false;
  79005. this._lastFrameTime = null;
  79006. this._lastInteractionTime = -Infinity;
  79007. this._cameraRotationSpeed = 0;
  79008. this._lastFrameRadius = 0;
  79009. }
  79010. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79011. get: function () {
  79012. return "AutoRotation";
  79013. },
  79014. enumerable: true,
  79015. configurable: true
  79016. });
  79017. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79018. /**
  79019. * Gets the flag that indicates if user zooming should stop animation.
  79020. */
  79021. get: function () {
  79022. return this._zoomStopsAnimation;
  79023. },
  79024. /**
  79025. * Sets the flag that indicates if user zooming should stop animation.
  79026. */
  79027. set: function (flag) {
  79028. this._zoomStopsAnimation = flag;
  79029. },
  79030. enumerable: true,
  79031. configurable: true
  79032. });
  79033. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79034. /**
  79035. * Gets the default speed at which the camera rotates around the model.
  79036. */
  79037. get: function () {
  79038. return this._idleRotationSpeed;
  79039. },
  79040. /**
  79041. * Sets the default speed at which the camera rotates around the model.
  79042. */
  79043. set: function (speed) {
  79044. this._idleRotationSpeed = speed;
  79045. },
  79046. enumerable: true,
  79047. configurable: true
  79048. });
  79049. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79050. /**
  79051. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79052. */
  79053. get: function () {
  79054. return this._idleRotationWaitTime;
  79055. },
  79056. /**
  79057. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79058. */
  79059. set: function (time) {
  79060. this._idleRotationWaitTime = time;
  79061. },
  79062. enumerable: true,
  79063. configurable: true
  79064. });
  79065. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79066. /**
  79067. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79068. */
  79069. get: function () {
  79070. return this._idleRotationSpinupTime;
  79071. },
  79072. /**
  79073. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79074. */
  79075. set: function (time) {
  79076. this._idleRotationSpinupTime = time;
  79077. },
  79078. enumerable: true,
  79079. configurable: true
  79080. });
  79081. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79082. /**
  79083. * Gets a value indicating if the camera is currently rotating because of this behavior
  79084. */
  79085. get: function () {
  79086. return Math.abs(this._cameraRotationSpeed) > 0;
  79087. },
  79088. enumerable: true,
  79089. configurable: true
  79090. });
  79091. AutoRotationBehavior.prototype.init = function () {
  79092. // Do notihng
  79093. };
  79094. AutoRotationBehavior.prototype.attach = function (camera) {
  79095. var _this = this;
  79096. this._attachedCamera = camera;
  79097. var scene = this._attachedCamera.getScene();
  79098. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79099. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79100. _this._isPointerDown = true;
  79101. return;
  79102. }
  79103. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79104. _this._isPointerDown = false;
  79105. }
  79106. });
  79107. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79108. var now = BABYLON.Tools.Now;
  79109. var dt = 0;
  79110. if (_this._lastFrameTime != null) {
  79111. dt = now - _this._lastFrameTime;
  79112. }
  79113. _this._lastFrameTime = now;
  79114. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79115. _this._applyUserInteraction();
  79116. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79117. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79118. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79119. // Step camera rotation by rotation speed
  79120. if (_this._attachedCamera) {
  79121. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79122. }
  79123. });
  79124. };
  79125. AutoRotationBehavior.prototype.detach = function () {
  79126. if (!this._attachedCamera) {
  79127. return;
  79128. }
  79129. var scene = this._attachedCamera.getScene();
  79130. if (this._onPrePointerObservableObserver) {
  79131. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79132. }
  79133. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79134. this._attachedCamera = null;
  79135. };
  79136. /**
  79137. * Returns true if user is scrolling.
  79138. * @return true if user is scrolling.
  79139. */
  79140. AutoRotationBehavior.prototype._userIsZooming = function () {
  79141. if (!this._attachedCamera) {
  79142. return false;
  79143. }
  79144. return this._attachedCamera.inertialRadiusOffset !== 0;
  79145. };
  79146. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79147. if (!this._attachedCamera) {
  79148. return false;
  79149. }
  79150. var zoomHasHitLimit = false;
  79151. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79152. zoomHasHitLimit = true;
  79153. }
  79154. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79155. this._lastFrameRadius = this._attachedCamera.radius;
  79156. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79157. };
  79158. /**
  79159. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79160. */
  79161. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79162. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79163. this._lastInteractionTime = BABYLON.Tools.Now;
  79164. }
  79165. };
  79166. // Tools
  79167. AutoRotationBehavior.prototype._userIsMoving = function () {
  79168. if (!this._attachedCamera) {
  79169. return false;
  79170. }
  79171. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79172. this._attachedCamera.inertialBetaOffset !== 0 ||
  79173. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79174. this._attachedCamera.inertialPanningX !== 0 ||
  79175. this._attachedCamera.inertialPanningY !== 0 ||
  79176. this._isPointerDown;
  79177. };
  79178. return AutoRotationBehavior;
  79179. }());
  79180. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79181. })(BABYLON || (BABYLON = {}));
  79182. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79183. var BABYLON;
  79184. (function (BABYLON) {
  79185. /**
  79186. * This class can be used to get instrumentation data from a Babylon engine
  79187. */
  79188. var EngineInstrumentation = /** @class */ (function () {
  79189. function EngineInstrumentation(engine) {
  79190. this.engine = engine;
  79191. this._captureGPUFrameTime = false;
  79192. this._gpuFrameTime = new BABYLON.PerfCounter();
  79193. this._captureShaderCompilationTime = false;
  79194. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79195. // Observers
  79196. this._onBeginFrameObserver = null;
  79197. this._onEndFrameObserver = null;
  79198. this._onBeforeShaderCompilationObserver = null;
  79199. this._onAfterShaderCompilationObserver = null;
  79200. }
  79201. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79202. // Properties
  79203. /**
  79204. * Gets the perf counter used for GPU frame time
  79205. */
  79206. get: function () {
  79207. return this._gpuFrameTime;
  79208. },
  79209. enumerable: true,
  79210. configurable: true
  79211. });
  79212. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79213. /**
  79214. * Gets the GPU frame time capture status
  79215. */
  79216. get: function () {
  79217. return this._captureGPUFrameTime;
  79218. },
  79219. /**
  79220. * Enable or disable the GPU frame time capture
  79221. */
  79222. set: function (value) {
  79223. var _this = this;
  79224. if (value === this._captureGPUFrameTime) {
  79225. return;
  79226. }
  79227. this._captureGPUFrameTime = value;
  79228. if (value) {
  79229. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79230. if (!_this._gpuFrameTimeToken) {
  79231. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79232. }
  79233. });
  79234. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79235. if (!_this._gpuFrameTimeToken) {
  79236. return;
  79237. }
  79238. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79239. if (time > -1) {
  79240. _this._gpuFrameTimeToken = null;
  79241. _this._gpuFrameTime.fetchNewFrame();
  79242. _this._gpuFrameTime.addCount(time, true);
  79243. }
  79244. });
  79245. }
  79246. else {
  79247. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79248. this._onBeginFrameObserver = null;
  79249. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79250. this._onEndFrameObserver = null;
  79251. }
  79252. },
  79253. enumerable: true,
  79254. configurable: true
  79255. });
  79256. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79257. /**
  79258. * Gets the perf counter used for shader compilation time
  79259. */
  79260. get: function () {
  79261. return this._shaderCompilationTime;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79267. /**
  79268. * Gets the shader compilation time capture status
  79269. */
  79270. get: function () {
  79271. return this._captureShaderCompilationTime;
  79272. },
  79273. /**
  79274. * Enable or disable the shader compilation time capture
  79275. */
  79276. set: function (value) {
  79277. var _this = this;
  79278. if (value === this._captureShaderCompilationTime) {
  79279. return;
  79280. }
  79281. this._captureShaderCompilationTime = value;
  79282. if (value) {
  79283. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79284. _this._shaderCompilationTime.fetchNewFrame();
  79285. _this._shaderCompilationTime.beginMonitoring();
  79286. });
  79287. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79288. _this._shaderCompilationTime.endMonitoring();
  79289. });
  79290. }
  79291. else {
  79292. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79293. this._onBeforeShaderCompilationObserver = null;
  79294. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79295. this._onAfterShaderCompilationObserver = null;
  79296. }
  79297. },
  79298. enumerable: true,
  79299. configurable: true
  79300. });
  79301. EngineInstrumentation.prototype.dispose = function () {
  79302. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79303. this._onBeginFrameObserver = null;
  79304. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79305. this._onEndFrameObserver = null;
  79306. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79307. this._onBeforeShaderCompilationObserver = null;
  79308. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79309. this._onAfterShaderCompilationObserver = null;
  79310. this.engine = null;
  79311. };
  79312. return EngineInstrumentation;
  79313. }());
  79314. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79315. })(BABYLON || (BABYLON = {}));
  79316. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79317. var BABYLON;
  79318. (function (BABYLON) {
  79319. /**
  79320. * This class can be used to get instrumentation data from a Babylon engine
  79321. */
  79322. var SceneInstrumentation = /** @class */ (function () {
  79323. function SceneInstrumentation(scene) {
  79324. var _this = this;
  79325. this.scene = scene;
  79326. this._captureActiveMeshesEvaluationTime = false;
  79327. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79328. this._captureRenderTargetsRenderTime = false;
  79329. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79330. this._captureFrameTime = false;
  79331. this._frameTime = new BABYLON.PerfCounter();
  79332. this._captureRenderTime = false;
  79333. this._renderTime = new BABYLON.PerfCounter();
  79334. this._captureInterFrameTime = false;
  79335. this._interFrameTime = new BABYLON.PerfCounter();
  79336. this._captureParticlesRenderTime = false;
  79337. this._particlesRenderTime = new BABYLON.PerfCounter();
  79338. this._captureSpritesRenderTime = false;
  79339. this._spritesRenderTime = new BABYLON.PerfCounter();
  79340. this._capturePhysicsTime = false;
  79341. this._physicsTime = new BABYLON.PerfCounter();
  79342. this._captureAnimationsTime = false;
  79343. this._animationsTime = new BABYLON.PerfCounter();
  79344. // Observers
  79345. this._onBeforeActiveMeshesEvaluationObserver = null;
  79346. this._onAfterActiveMeshesEvaluationObserver = null;
  79347. this._onBeforeRenderTargetsRenderObserver = null;
  79348. this._onAfterRenderTargetsRenderObserver = null;
  79349. this._onAfterRenderObserver = null;
  79350. this._onBeforeDrawPhaseObserver = null;
  79351. this._onAfterDrawPhaseObserver = null;
  79352. this._onBeforeAnimationsObserver = null;
  79353. this._onBeforeParticlesRenderingObserver = null;
  79354. this._onAfterParticlesRenderingObserver = null;
  79355. this._onBeforeSpritesRenderingObserver = null;
  79356. this._onAfterSpritesRenderingObserver = null;
  79357. this._onBeforePhysicsObserver = null;
  79358. this._onAfterPhysicsObserver = null;
  79359. this._onAfterAnimationsObserver = null;
  79360. // Before render
  79361. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79362. if (_this._captureActiveMeshesEvaluationTime) {
  79363. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79364. }
  79365. if (_this._captureRenderTargetsRenderTime) {
  79366. _this._renderTargetsRenderTime.fetchNewFrame();
  79367. }
  79368. if (_this._captureFrameTime) {
  79369. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79370. _this._frameTime.beginMonitoring();
  79371. }
  79372. if (_this._captureInterFrameTime) {
  79373. _this._interFrameTime.endMonitoring();
  79374. }
  79375. if (_this._captureParticlesRenderTime) {
  79376. _this._particlesRenderTime.fetchNewFrame();
  79377. }
  79378. if (_this._captureSpritesRenderTime) {
  79379. _this._spritesRenderTime.fetchNewFrame();
  79380. }
  79381. if (_this._captureAnimationsTime) {
  79382. _this._animationsTime.beginMonitoring();
  79383. }
  79384. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79385. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79386. });
  79387. // After render
  79388. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79389. if (_this._captureFrameTime) {
  79390. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79391. _this._frameTime.endMonitoring();
  79392. }
  79393. if (_this._captureRenderTime) {
  79394. _this._renderTime.endMonitoring(false);
  79395. }
  79396. if (_this._captureInterFrameTime) {
  79397. _this._interFrameTime.beginMonitoring();
  79398. }
  79399. });
  79400. }
  79401. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79402. // Properties
  79403. /**
  79404. * Gets the perf counter used for active meshes evaluation time
  79405. */
  79406. get: function () {
  79407. return this._activeMeshesEvaluationTime;
  79408. },
  79409. enumerable: true,
  79410. configurable: true
  79411. });
  79412. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79413. /**
  79414. * Gets the active meshes evaluation time capture status
  79415. */
  79416. get: function () {
  79417. return this._captureActiveMeshesEvaluationTime;
  79418. },
  79419. /**
  79420. * Enable or disable the active meshes evaluation time capture
  79421. */
  79422. set: function (value) {
  79423. var _this = this;
  79424. if (value === this._captureActiveMeshesEvaluationTime) {
  79425. return;
  79426. }
  79427. this._captureActiveMeshesEvaluationTime = value;
  79428. if (value) {
  79429. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79430. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79431. _this._activeMeshesEvaluationTime.beginMonitoring();
  79432. });
  79433. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79434. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79435. _this._activeMeshesEvaluationTime.endMonitoring();
  79436. });
  79437. }
  79438. else {
  79439. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79440. this._onBeforeActiveMeshesEvaluationObserver = null;
  79441. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79442. this._onAfterActiveMeshesEvaluationObserver = null;
  79443. }
  79444. },
  79445. enumerable: true,
  79446. configurable: true
  79447. });
  79448. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79449. /**
  79450. * Gets the perf counter used for render targets render time
  79451. */
  79452. get: function () {
  79453. return this._renderTargetsRenderTime;
  79454. },
  79455. enumerable: true,
  79456. configurable: true
  79457. });
  79458. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79459. /**
  79460. * Gets the render targets render time capture status
  79461. */
  79462. get: function () {
  79463. return this._captureRenderTargetsRenderTime;
  79464. },
  79465. /**
  79466. * Enable or disable the render targets render time capture
  79467. */
  79468. set: function (value) {
  79469. var _this = this;
  79470. if (value === this._captureRenderTargetsRenderTime) {
  79471. return;
  79472. }
  79473. this._captureRenderTargetsRenderTime = value;
  79474. if (value) {
  79475. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79476. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79477. _this._renderTargetsRenderTime.beginMonitoring();
  79478. });
  79479. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79480. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79481. _this._renderTargetsRenderTime.endMonitoring(false);
  79482. });
  79483. }
  79484. else {
  79485. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79486. this._onBeforeRenderTargetsRenderObserver = null;
  79487. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79488. this._onAfterRenderTargetsRenderObserver = null;
  79489. }
  79490. },
  79491. enumerable: true,
  79492. configurable: true
  79493. });
  79494. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79495. /**
  79496. * Gets the perf counter used for particles render time
  79497. */
  79498. get: function () {
  79499. return this._particlesRenderTime;
  79500. },
  79501. enumerable: true,
  79502. configurable: true
  79503. });
  79504. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79505. /**
  79506. * Gets the particles render time capture status
  79507. */
  79508. get: function () {
  79509. return this._captureParticlesRenderTime;
  79510. },
  79511. /**
  79512. * Enable or disable the particles render time capture
  79513. */
  79514. set: function (value) {
  79515. var _this = this;
  79516. if (value === this._captureParticlesRenderTime) {
  79517. return;
  79518. }
  79519. this._captureParticlesRenderTime = value;
  79520. if (value) {
  79521. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79522. BABYLON.Tools.StartPerformanceCounter("Particles");
  79523. _this._particlesRenderTime.beginMonitoring();
  79524. });
  79525. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79526. BABYLON.Tools.EndPerformanceCounter("Particles");
  79527. _this._particlesRenderTime.endMonitoring(false);
  79528. });
  79529. }
  79530. else {
  79531. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79532. this._onBeforeParticlesRenderingObserver = null;
  79533. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79534. this._onAfterParticlesRenderingObserver = null;
  79535. }
  79536. },
  79537. enumerable: true,
  79538. configurable: true
  79539. });
  79540. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79541. /**
  79542. * Gets the perf counter used for sprites render time
  79543. */
  79544. get: function () {
  79545. return this._spritesRenderTime;
  79546. },
  79547. enumerable: true,
  79548. configurable: true
  79549. });
  79550. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79551. /**
  79552. * Gets the sprites render time capture status
  79553. */
  79554. get: function () {
  79555. return this._captureSpritesRenderTime;
  79556. },
  79557. /**
  79558. * Enable or disable the sprites render time capture
  79559. */
  79560. set: function (value) {
  79561. var _this = this;
  79562. if (value === this._captureSpritesRenderTime) {
  79563. return;
  79564. }
  79565. this._captureSpritesRenderTime = value;
  79566. if (value) {
  79567. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79568. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79569. _this._spritesRenderTime.beginMonitoring();
  79570. });
  79571. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79572. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79573. _this._spritesRenderTime.endMonitoring(false);
  79574. });
  79575. }
  79576. else {
  79577. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79578. this._onBeforeSpritesRenderingObserver = null;
  79579. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79580. this._onAfterSpritesRenderingObserver = null;
  79581. }
  79582. },
  79583. enumerable: true,
  79584. configurable: true
  79585. });
  79586. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79587. /**
  79588. * Gets the perf counter used for physics time
  79589. */
  79590. get: function () {
  79591. return this._physicsTime;
  79592. },
  79593. enumerable: true,
  79594. configurable: true
  79595. });
  79596. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79597. /**
  79598. * Gets the physics time capture status
  79599. */
  79600. get: function () {
  79601. return this._capturePhysicsTime;
  79602. },
  79603. /**
  79604. * Enable or disable the physics time capture
  79605. */
  79606. set: function (value) {
  79607. var _this = this;
  79608. if (value === this._capturePhysicsTime) {
  79609. return;
  79610. }
  79611. this._capturePhysicsTime = value;
  79612. if (value) {
  79613. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  79614. BABYLON.Tools.StartPerformanceCounter("Physics");
  79615. _this._physicsTime.beginMonitoring();
  79616. });
  79617. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  79618. BABYLON.Tools.EndPerformanceCounter("Physics");
  79619. _this._physicsTime.endMonitoring();
  79620. });
  79621. }
  79622. else {
  79623. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79624. this._onBeforePhysicsObserver = null;
  79625. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79626. this._onAfterPhysicsObserver = null;
  79627. }
  79628. },
  79629. enumerable: true,
  79630. configurable: true
  79631. });
  79632. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  79633. /**
  79634. * Gets the perf counter used for animations time
  79635. */
  79636. get: function () {
  79637. return this._animationsTime;
  79638. },
  79639. enumerable: true,
  79640. configurable: true
  79641. });
  79642. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  79643. /**
  79644. * Gets the animations time capture status
  79645. */
  79646. get: function () {
  79647. return this._captureAnimationsTime;
  79648. },
  79649. /**
  79650. * Enable or disable the animations time capture
  79651. */
  79652. set: function (value) {
  79653. var _this = this;
  79654. if (value === this._captureAnimationsTime) {
  79655. return;
  79656. }
  79657. this._captureAnimationsTime = value;
  79658. if (value) {
  79659. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  79660. _this._animationsTime.endMonitoring();
  79661. });
  79662. }
  79663. else {
  79664. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79665. this._onAfterAnimationsObserver = null;
  79666. }
  79667. },
  79668. enumerable: true,
  79669. configurable: true
  79670. });
  79671. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  79672. /**
  79673. * Gets the perf counter used for frame time capture
  79674. */
  79675. get: function () {
  79676. return this._frameTime;
  79677. },
  79678. enumerable: true,
  79679. configurable: true
  79680. });
  79681. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  79682. /**
  79683. * Gets the frame time capture status
  79684. */
  79685. get: function () {
  79686. return this._captureFrameTime;
  79687. },
  79688. /**
  79689. * Enable or disable the frame time capture
  79690. */
  79691. set: function (value) {
  79692. this._captureFrameTime = value;
  79693. },
  79694. enumerable: true,
  79695. configurable: true
  79696. });
  79697. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  79698. /**
  79699. * Gets the perf counter used for inter-frames time capture
  79700. */
  79701. get: function () {
  79702. return this._interFrameTime;
  79703. },
  79704. enumerable: true,
  79705. configurable: true
  79706. });
  79707. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  79708. /**
  79709. * Gets the inter-frames time capture status
  79710. */
  79711. get: function () {
  79712. return this._captureInterFrameTime;
  79713. },
  79714. /**
  79715. * Enable or disable the inter-frames time capture
  79716. */
  79717. set: function (value) {
  79718. this._captureInterFrameTime = value;
  79719. },
  79720. enumerable: true,
  79721. configurable: true
  79722. });
  79723. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  79724. /**
  79725. * Gets the perf counter used for render time capture
  79726. */
  79727. get: function () {
  79728. return this._renderTime;
  79729. },
  79730. enumerable: true,
  79731. configurable: true
  79732. });
  79733. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  79734. /**
  79735. * Gets the render time capture status
  79736. */
  79737. get: function () {
  79738. return this._captureRenderTime;
  79739. },
  79740. /**
  79741. * Enable or disable the render time capture
  79742. */
  79743. set: function (value) {
  79744. var _this = this;
  79745. if (value === this._captureRenderTime) {
  79746. return;
  79747. }
  79748. this._captureRenderTime = value;
  79749. if (value) {
  79750. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  79751. _this._renderTime.beginMonitoring();
  79752. BABYLON.Tools.StartPerformanceCounter("Main render");
  79753. });
  79754. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  79755. _this._renderTime.endMonitoring(false);
  79756. BABYLON.Tools.EndPerformanceCounter("Main render");
  79757. });
  79758. }
  79759. else {
  79760. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79761. this._onBeforeDrawPhaseObserver = null;
  79762. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79763. this._onAfterDrawPhaseObserver = null;
  79764. }
  79765. },
  79766. enumerable: true,
  79767. configurable: true
  79768. });
  79769. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  79770. /**
  79771. * Gets the perf counter used for draw calls
  79772. */
  79773. get: function () {
  79774. return this.scene.getEngine()._drawCalls;
  79775. },
  79776. enumerable: true,
  79777. configurable: true
  79778. });
  79779. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  79780. /**
  79781. * Gets the perf counter used for texture collisions
  79782. */
  79783. get: function () {
  79784. return this.scene.getEngine()._textureCollisions;
  79785. },
  79786. enumerable: true,
  79787. configurable: true
  79788. });
  79789. SceneInstrumentation.prototype.dispose = function () {
  79790. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  79791. this._onAfterRenderObserver = null;
  79792. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79793. this._onBeforeActiveMeshesEvaluationObserver = null;
  79794. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79795. this._onAfterActiveMeshesEvaluationObserver = null;
  79796. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79797. this._onBeforeRenderTargetsRenderObserver = null;
  79798. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79799. this._onAfterRenderTargetsRenderObserver = null;
  79800. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  79801. this._onBeforeAnimationsObserver = null;
  79802. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79803. this._onBeforeParticlesRenderingObserver = null;
  79804. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79805. this._onAfterParticlesRenderingObserver = null;
  79806. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79807. this._onBeforeSpritesRenderingObserver = null;
  79808. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79809. this._onAfterSpritesRenderingObserver = null;
  79810. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79811. this._onBeforeDrawPhaseObserver = null;
  79812. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79813. this._onAfterDrawPhaseObserver = null;
  79814. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79815. this._onBeforePhysicsObserver = null;
  79816. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79817. this._onAfterPhysicsObserver = null;
  79818. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79819. this._onAfterAnimationsObserver = null;
  79820. this.scene = null;
  79821. };
  79822. return SceneInstrumentation;
  79823. }());
  79824. BABYLON.SceneInstrumentation = SceneInstrumentation;
  79825. })(BABYLON || (BABYLON = {}));
  79826. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  79827. var BABYLON;
  79828. (function (BABYLON) {
  79829. var _TimeToken = /** @class */ (function () {
  79830. function _TimeToken() {
  79831. this._timeElapsedQueryEnded = false;
  79832. }
  79833. return _TimeToken;
  79834. }());
  79835. BABYLON._TimeToken = _TimeToken;
  79836. })(BABYLON || (BABYLON = {}));
  79837. //# sourceMappingURL=babylon.timeToken.js.map
  79838. var BABYLON;
  79839. (function (BABYLON) {
  79840. /**
  79841. * Background material defines definition.
  79842. */
  79843. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  79844. __extends(BackgroundMaterialDefines, _super);
  79845. /**
  79846. * Constructor of the defines.
  79847. */
  79848. function BackgroundMaterialDefines() {
  79849. var _this = _super.call(this) || this;
  79850. /**
  79851. * True if the diffuse texture is in use.
  79852. */
  79853. _this.DIFFUSE = false;
  79854. /**
  79855. * The direct UV channel to use.
  79856. */
  79857. _this.DIFFUSEDIRECTUV = 0;
  79858. /**
  79859. * True if the diffuse texture is in gamma space.
  79860. */
  79861. _this.GAMMADIFFUSE = false;
  79862. /**
  79863. * True if the diffuse texture has opacity in the alpha channel.
  79864. */
  79865. _this.DIFFUSEHASALPHA = false;
  79866. /**
  79867. * True if you want the material to fade to transparent at grazing angle.
  79868. */
  79869. _this.OPACITYFRESNEL = false;
  79870. /**
  79871. * True if an extra blur needs to be added in the reflection.
  79872. */
  79873. _this.REFLECTIONBLUR = false;
  79874. /**
  79875. * True if you want the material to fade to reflection at grazing angle.
  79876. */
  79877. _this.REFLECTIONFRESNEL = false;
  79878. /**
  79879. * True if you want the material to falloff as far as you move away from the scene center.
  79880. */
  79881. _this.REFLECTIONFALLOFF = false;
  79882. /**
  79883. * False if the current Webgl implementation does not support the texture lod extension.
  79884. */
  79885. _this.TEXTURELODSUPPORT = false;
  79886. /**
  79887. * True to ensure the data are premultiplied.
  79888. */
  79889. _this.PREMULTIPLYALPHA = false;
  79890. /**
  79891. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  79892. */
  79893. _this.USERGBCOLOR = false;
  79894. /**
  79895. * True to add noise in order to reduce the banding effect.
  79896. */
  79897. _this.NOISE = false;
  79898. // Image Processing Configuration.
  79899. _this.IMAGEPROCESSING = false;
  79900. _this.VIGNETTE = false;
  79901. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79902. _this.VIGNETTEBLENDMODEOPAQUE = false;
  79903. _this.TONEMAPPING = false;
  79904. _this.CONTRAST = false;
  79905. _this.COLORCURVES = false;
  79906. _this.COLORGRADING = false;
  79907. _this.COLORGRADING3D = false;
  79908. _this.SAMPLER3DGREENDEPTH = false;
  79909. _this.SAMPLER3DBGRMAP = false;
  79910. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  79911. _this.EXPOSURE = false;
  79912. // Reflection.
  79913. _this.REFLECTION = false;
  79914. _this.REFLECTIONMAP_3D = false;
  79915. _this.REFLECTIONMAP_SPHERICAL = false;
  79916. _this.REFLECTIONMAP_PLANAR = false;
  79917. _this.REFLECTIONMAP_CUBIC = false;
  79918. _this.REFLECTIONMAP_PROJECTION = false;
  79919. _this.REFLECTIONMAP_SKYBOX = false;
  79920. _this.REFLECTIONMAP_EXPLICIT = false;
  79921. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  79922. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  79923. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  79924. _this.INVERTCUBICMAP = false;
  79925. _this.REFLECTIONMAP_OPPOSITEZ = false;
  79926. _this.LODINREFLECTIONALPHA = false;
  79927. _this.GAMMAREFLECTION = false;
  79928. // Default BJS.
  79929. _this.MAINUV1 = false;
  79930. _this.MAINUV2 = false;
  79931. _this.UV1 = false;
  79932. _this.UV2 = false;
  79933. _this.CLIPPLANE = false;
  79934. _this.POINTSIZE = false;
  79935. _this.FOG = false;
  79936. _this.NORMAL = false;
  79937. _this.NUM_BONE_INFLUENCERS = 0;
  79938. _this.BonesPerMesh = 0;
  79939. _this.INSTANCES = false;
  79940. _this.SHADOWFLOAT = false;
  79941. _this.rebuild();
  79942. return _this;
  79943. }
  79944. return BackgroundMaterialDefines;
  79945. }(BABYLON.MaterialDefines));
  79946. /**
  79947. * Background material used to create an efficient environement around your scene.
  79948. */
  79949. var BackgroundMaterial = /** @class */ (function (_super) {
  79950. __extends(BackgroundMaterial, _super);
  79951. /**
  79952. * constructor
  79953. * @param name The name of the material
  79954. * @param scene The scene to add the material to
  79955. */
  79956. function BackgroundMaterial(name, scene) {
  79957. var _this = _super.call(this, name, scene) || this;
  79958. _this.primaryColor = BABYLON.Color3.White();
  79959. _this.primaryLevel = 1;
  79960. _this.secondaryColor = BABYLON.Color3.Gray();
  79961. _this.secondaryLevel = 1;
  79962. _this.tertiaryColor = BABYLON.Color3.Black();
  79963. _this.tertiaryLevel = 1;
  79964. _this.reflectionTexture = null;
  79965. _this.reflectionBlur = 0;
  79966. _this.diffuseTexture = null;
  79967. /**
  79968. * Specify the list of lights casting shadow on the material.
  79969. * All scene shadow lights will be included if null.
  79970. */
  79971. _this._shadowLights = null;
  79972. _this.shadowLights = null;
  79973. _this.shadowBlurScale = 1;
  79974. _this.shadowLevel = 0;
  79975. _this.sceneCenter = BABYLON.Vector3.Zero();
  79976. _this.opacityFresnel = true;
  79977. _this.reflectionFresnel = false;
  79978. _this.reflectionFalloffDistance = 0.0;
  79979. _this.reflectionAmount = 1.0;
  79980. _this.reflectionReflectance0 = 0.05;
  79981. _this.reflectionReflectance90 = 0.5;
  79982. _this.useRGBColor = true;
  79983. _this.enableNoise = false;
  79984. /**
  79985. * Number of Simultaneous lights allowed on the material.
  79986. */
  79987. _this._maxSimultaneousLights = 4;
  79988. _this.maxSimultaneousLights = 4;
  79989. /**
  79990. * Keep track of the image processing observer to allow dispose and replace.
  79991. */
  79992. _this._imageProcessingObserver = null;
  79993. // Temp values kept as cache in the material.
  79994. _this._renderTargets = new BABYLON.SmartArray(16);
  79995. _this._reflectionControls = BABYLON.Vector4.Zero();
  79996. // Setup the default processing configuration to the scene.
  79997. _this._attachImageProcessingConfiguration(null);
  79998. _this.getRenderTargetTextures = function () {
  79999. _this._renderTargets.reset();
  80000. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80001. _this._renderTargets.push(_this._diffuseTexture);
  80002. }
  80003. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80004. _this._renderTargets.push(_this._reflectionTexture);
  80005. }
  80006. return _this._renderTargets;
  80007. };
  80008. return _this;
  80009. }
  80010. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80011. /**
  80012. * Sets the reflection reflectance fresnel values according to the default standard
  80013. * empirically know to work well :-)
  80014. */
  80015. set: function (value) {
  80016. var reflectionWeight = value;
  80017. if (reflectionWeight < 0.5) {
  80018. reflectionWeight = reflectionWeight * 2.0;
  80019. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80020. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80021. }
  80022. else {
  80023. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80024. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80025. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80026. }
  80027. },
  80028. enumerable: true,
  80029. configurable: true
  80030. });
  80031. /**
  80032. * Attaches a new image processing configuration to the PBR Material.
  80033. * @param configuration (if null the scene configuration will be use)
  80034. */
  80035. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80036. var _this = this;
  80037. if (configuration === this._imageProcessingConfiguration) {
  80038. return;
  80039. }
  80040. // Detaches observer.
  80041. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80042. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80043. }
  80044. // Pick the scene configuration if needed.
  80045. if (!configuration) {
  80046. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80047. }
  80048. else {
  80049. this._imageProcessingConfiguration = configuration;
  80050. }
  80051. // Attaches observer.
  80052. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80053. _this._markAllSubMeshesAsImageProcessingDirty();
  80054. });
  80055. };
  80056. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80057. /**
  80058. * Gets the image processing configuration used either in this material.
  80059. */
  80060. get: function () {
  80061. return this._imageProcessingConfiguration;
  80062. },
  80063. /**
  80064. * Sets the Default image processing configuration used either in the this material.
  80065. *
  80066. * If sets to null, the scene one is in use.
  80067. */
  80068. set: function (value) {
  80069. this._attachImageProcessingConfiguration(value);
  80070. // Ensure the effect will be rebuilt.
  80071. this._markAllSubMeshesAsTexturesDirty();
  80072. },
  80073. enumerable: true,
  80074. configurable: true
  80075. });
  80076. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80077. /**
  80078. * Gets wether the color curves effect is enabled.
  80079. */
  80080. get: function () {
  80081. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80082. },
  80083. /**
  80084. * Sets wether the color curves effect is enabled.
  80085. */
  80086. set: function (value) {
  80087. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80088. },
  80089. enumerable: true,
  80090. configurable: true
  80091. });
  80092. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80093. /**
  80094. * Gets wether the color grading effect is enabled.
  80095. */
  80096. get: function () {
  80097. return this.imageProcessingConfiguration.colorGradingEnabled;
  80098. },
  80099. /**
  80100. * Gets wether the color grading effect is enabled.
  80101. */
  80102. set: function (value) {
  80103. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80104. },
  80105. enumerable: true,
  80106. configurable: true
  80107. });
  80108. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80109. /**
  80110. * Gets wether tonemapping is enabled or not.
  80111. */
  80112. get: function () {
  80113. return this._imageProcessingConfiguration.toneMappingEnabled;
  80114. },
  80115. /**
  80116. * Sets wether tonemapping is enabled or not
  80117. */
  80118. set: function (value) {
  80119. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80120. },
  80121. enumerable: true,
  80122. configurable: true
  80123. });
  80124. ;
  80125. ;
  80126. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80127. /**
  80128. * The camera exposure used on this material.
  80129. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80130. * This corresponds to a photographic exposure.
  80131. */
  80132. get: function () {
  80133. return this._imageProcessingConfiguration.exposure;
  80134. },
  80135. /**
  80136. * The camera exposure used on this material.
  80137. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80138. * This corresponds to a photographic exposure.
  80139. */
  80140. set: function (value) {
  80141. this._imageProcessingConfiguration.exposure = value;
  80142. },
  80143. enumerable: true,
  80144. configurable: true
  80145. });
  80146. ;
  80147. ;
  80148. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80149. /**
  80150. * Gets The camera contrast used on this material.
  80151. */
  80152. get: function () {
  80153. return this._imageProcessingConfiguration.contrast;
  80154. },
  80155. /**
  80156. * Sets The camera contrast used on this material.
  80157. */
  80158. set: function (value) {
  80159. this._imageProcessingConfiguration.contrast = value;
  80160. },
  80161. enumerable: true,
  80162. configurable: true
  80163. });
  80164. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80165. /**
  80166. * Gets the Color Grading 2D Lookup Texture.
  80167. */
  80168. get: function () {
  80169. return this._imageProcessingConfiguration.colorGradingTexture;
  80170. },
  80171. /**
  80172. * Sets the Color Grading 2D Lookup Texture.
  80173. */
  80174. set: function (value) {
  80175. this.imageProcessingConfiguration.colorGradingTexture = value;
  80176. },
  80177. enumerable: true,
  80178. configurable: true
  80179. });
  80180. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80181. /**
  80182. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80183. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80184. * 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;
  80185. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80186. */
  80187. get: function () {
  80188. return this.imageProcessingConfiguration.colorCurves;
  80189. },
  80190. /**
  80191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80193. * 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;
  80194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80195. */
  80196. set: function (value) {
  80197. this.imageProcessingConfiguration.colorCurves = value;
  80198. },
  80199. enumerable: true,
  80200. configurable: true
  80201. });
  80202. /**
  80203. * The entire material has been created in order to prevent overdraw.
  80204. * @returns false
  80205. */
  80206. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80207. return true;
  80208. };
  80209. /**
  80210. * The entire material has been created in order to prevent overdraw.
  80211. * @returns true if blending is enable
  80212. */
  80213. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80214. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80215. };
  80216. /**
  80217. * Checks wether the material is ready to be rendered for a given mesh.
  80218. * @param mesh The mesh to render
  80219. * @param subMesh The submesh to check against
  80220. * @param useInstances Specify wether or not the material is used with instances
  80221. */
  80222. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80223. var _this = this;
  80224. if (useInstances === void 0) { useInstances = false; }
  80225. if (subMesh.effect && this.isFrozen) {
  80226. if (this._wasPreviouslyReady) {
  80227. return true;
  80228. }
  80229. }
  80230. if (!subMesh._materialDefines) {
  80231. subMesh._materialDefines = new BackgroundMaterialDefines();
  80232. }
  80233. var scene = this.getScene();
  80234. var defines = subMesh._materialDefines;
  80235. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80236. if (defines._renderId === scene.getRenderId()) {
  80237. return true;
  80238. }
  80239. }
  80240. var engine = scene.getEngine();
  80241. // Lights
  80242. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80243. defines._needNormals = true;
  80244. // Textures
  80245. if (defines._areTexturesDirty) {
  80246. defines._needUVs = false;
  80247. if (scene.texturesEnabled) {
  80248. if (scene.getEngine().getCaps().textureLOD) {
  80249. defines.TEXTURELODSUPPORT = true;
  80250. }
  80251. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80252. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80253. return false;
  80254. }
  80255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80256. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80257. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80258. defines.OPACITYFRESNEL = this._opacityFresnel;
  80259. }
  80260. else {
  80261. defines.DIFFUSE = false;
  80262. defines.DIFFUSEHASALPHA = false;
  80263. defines.GAMMADIFFUSE = false;
  80264. defines.OPACITYFRESNEL = false;
  80265. }
  80266. var reflectionTexture = this._reflectionTexture;
  80267. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80268. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80269. return false;
  80270. }
  80271. defines.REFLECTION = true;
  80272. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80273. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80274. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80275. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80276. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80277. defines.INVERTCUBICMAP = true;
  80278. }
  80279. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80280. switch (reflectionTexture.coordinatesMode) {
  80281. case BABYLON.Texture.CUBIC_MODE:
  80282. case BABYLON.Texture.INVCUBIC_MODE:
  80283. defines.REFLECTIONMAP_CUBIC = true;
  80284. break;
  80285. case BABYLON.Texture.EXPLICIT_MODE:
  80286. defines.REFLECTIONMAP_EXPLICIT = true;
  80287. break;
  80288. case BABYLON.Texture.PLANAR_MODE:
  80289. defines.REFLECTIONMAP_PLANAR = true;
  80290. break;
  80291. case BABYLON.Texture.PROJECTION_MODE:
  80292. defines.REFLECTIONMAP_PROJECTION = true;
  80293. break;
  80294. case BABYLON.Texture.SKYBOX_MODE:
  80295. defines.REFLECTIONMAP_SKYBOX = true;
  80296. break;
  80297. case BABYLON.Texture.SPHERICAL_MODE:
  80298. defines.REFLECTIONMAP_SPHERICAL = true;
  80299. break;
  80300. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80301. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80302. break;
  80303. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80304. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80305. break;
  80306. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80307. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80308. break;
  80309. }
  80310. if (this.reflectionFresnel) {
  80311. defines.REFLECTIONFRESNEL = true;
  80312. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80313. this._reflectionControls.x = this.reflectionAmount;
  80314. this._reflectionControls.y = this.reflectionReflectance0;
  80315. this._reflectionControls.z = this.reflectionReflectance90;
  80316. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80317. }
  80318. else {
  80319. defines.REFLECTIONFRESNEL = false;
  80320. defines.REFLECTIONFALLOFF = false;
  80321. }
  80322. }
  80323. else {
  80324. defines.REFLECTION = false;
  80325. defines.REFLECTIONFALLOFF = false;
  80326. defines.REFLECTIONBLUR = false;
  80327. defines.REFLECTIONMAP_3D = false;
  80328. defines.REFLECTIONMAP_SPHERICAL = false;
  80329. defines.REFLECTIONMAP_PLANAR = false;
  80330. defines.REFLECTIONMAP_CUBIC = false;
  80331. defines.REFLECTIONMAP_PROJECTION = false;
  80332. defines.REFLECTIONMAP_SKYBOX = false;
  80333. defines.REFLECTIONMAP_EXPLICIT = false;
  80334. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80335. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80336. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80337. defines.INVERTCUBICMAP = false;
  80338. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80339. defines.LODINREFLECTIONALPHA = false;
  80340. defines.GAMMAREFLECTION = false;
  80341. }
  80342. }
  80343. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80344. defines.USERGBCOLOR = this._useRGBColor;
  80345. defines.NOISE = this._enableNoise;
  80346. }
  80347. if (defines._areImageProcessingDirty) {
  80348. if (!this._imageProcessingConfiguration.isReady()) {
  80349. return false;
  80350. }
  80351. this._imageProcessingConfiguration.prepareDefines(defines);
  80352. }
  80353. // Misc.
  80354. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80355. // Values that need to be evaluated on every frame
  80356. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80357. // Attribs
  80358. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80359. if (mesh) {
  80360. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80361. mesh.createNormals(true);
  80362. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80363. }
  80364. }
  80365. }
  80366. // Get correct effect
  80367. if (defines.isDirty) {
  80368. defines.markAsProcessed();
  80369. scene.resetCachedMaterial();
  80370. // Fallbacks
  80371. var fallbacks = new BABYLON.EffectFallbacks();
  80372. if (defines.FOG) {
  80373. fallbacks.addFallback(0, "FOG");
  80374. }
  80375. if (defines.POINTSIZE) {
  80376. fallbacks.addFallback(1, "POINTSIZE");
  80377. }
  80378. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80379. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80380. fallbacks.addCPUSkinningFallback(0, mesh);
  80381. }
  80382. //Attributes
  80383. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80384. if (defines.NORMAL) {
  80385. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80386. }
  80387. if (defines.UV1) {
  80388. attribs.push(BABYLON.VertexBuffer.UVKind);
  80389. }
  80390. if (defines.UV2) {
  80391. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80392. }
  80393. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80394. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80395. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80396. "vFogInfos", "vFogColor", "pointSize",
  80397. "vClipPlane", "mBones",
  80398. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80399. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80400. "shadowLevel", "alpha",
  80401. "vBackgroundCenter", "vReflectionControl",
  80402. "vDiffuseInfos", "diffuseMatrix",
  80403. ];
  80404. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80405. var uniformBuffers = ["Material", "Scene"];
  80406. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80407. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80408. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80409. uniformsNames: uniforms,
  80410. uniformBuffersNames: uniformBuffers,
  80411. samplers: samplers,
  80412. defines: defines,
  80413. maxSimultaneousLights: this._maxSimultaneousLights
  80414. });
  80415. var onCompiled = function (effect) {
  80416. if (_this.onCompiled) {
  80417. _this.onCompiled(effect);
  80418. }
  80419. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80420. };
  80421. var join = defines.toString();
  80422. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80423. attributes: attribs,
  80424. uniformsNames: uniforms,
  80425. uniformBuffersNames: uniformBuffers,
  80426. samplers: samplers,
  80427. defines: join,
  80428. fallbacks: fallbacks,
  80429. onCompiled: onCompiled,
  80430. onError: this.onError,
  80431. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80432. }, engine), defines);
  80433. this.buildUniformLayout();
  80434. }
  80435. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80436. return false;
  80437. }
  80438. defines._renderId = scene.getRenderId();
  80439. this._wasPreviouslyReady = true;
  80440. return true;
  80441. };
  80442. /**
  80443. * Build the uniform buffer used in the material.
  80444. */
  80445. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80446. // Order is important !
  80447. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80448. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80449. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80450. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80451. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80452. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80453. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80454. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80455. this._uniformBuffer.addUniform("pointSize", 1);
  80456. this._uniformBuffer.addUniform("shadowLevel", 1);
  80457. this._uniformBuffer.addUniform("alpha", 1);
  80458. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80459. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80460. this._uniformBuffer.create();
  80461. };
  80462. /**
  80463. * Unbind the material.
  80464. */
  80465. BackgroundMaterial.prototype.unbind = function () {
  80466. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80467. this._uniformBuffer.setTexture("diffuseSampler", null);
  80468. }
  80469. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80470. this._uniformBuffer.setTexture("reflectionSampler", null);
  80471. }
  80472. _super.prototype.unbind.call(this);
  80473. };
  80474. /**
  80475. * Bind only the world matrix to the material.
  80476. * @param world The world matrix to bind.
  80477. */
  80478. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80479. this._activeEffect.setMatrix("world", world);
  80480. };
  80481. /**
  80482. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80483. * @param world The world matrix to bind.
  80484. * @param subMesh The submesh to bind for.
  80485. */
  80486. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80487. var scene = this.getScene();
  80488. var defines = subMesh._materialDefines;
  80489. if (!defines) {
  80490. return;
  80491. }
  80492. var effect = subMesh.effect;
  80493. if (!effect) {
  80494. return;
  80495. }
  80496. this._activeEffect = effect;
  80497. // Matrices
  80498. this.bindOnlyWorldMatrix(world);
  80499. // Bones
  80500. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80501. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80502. if (mustRebind) {
  80503. this._uniformBuffer.bindToEffect(effect, "Material");
  80504. this.bindViewProjection(effect);
  80505. var reflectionTexture = this._reflectionTexture;
  80506. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80507. // Texture uniforms
  80508. if (scene.texturesEnabled) {
  80509. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80510. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80511. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80512. }
  80513. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80514. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80515. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80516. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80517. }
  80518. }
  80519. if (this.shadowLevel > 0) {
  80520. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80521. }
  80522. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80523. // Point size
  80524. if (this.pointsCloud) {
  80525. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80526. }
  80527. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80528. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80529. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80530. }
  80531. // Textures
  80532. if (scene.texturesEnabled) {
  80533. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80534. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80535. }
  80536. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80537. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80538. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80539. }
  80540. else if (!defines.REFLECTIONBLUR) {
  80541. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80542. }
  80543. else {
  80544. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80545. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80546. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80547. }
  80548. if (defines.REFLECTIONFRESNEL) {
  80549. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80550. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80551. }
  80552. }
  80553. }
  80554. // Clip plane
  80555. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80556. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80557. }
  80558. if (mustRebind || !this.isFrozen) {
  80559. if (scene.lightsEnabled) {
  80560. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80561. }
  80562. // View
  80563. this.bindView(effect);
  80564. // Fog
  80565. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80566. // image processing
  80567. this._imageProcessingConfiguration.bind(this._activeEffect);
  80568. }
  80569. this._uniformBuffer.update();
  80570. this._afterBind(mesh);
  80571. };
  80572. /**
  80573. * Dispose the material.
  80574. * @forceDisposeEffect Force disposal of the associated effect.
  80575. * @forceDisposeTextures Force disposal of the associated textures.
  80576. */
  80577. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80578. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80579. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80580. if (forceDisposeTextures) {
  80581. if (this.diffuseTexture) {
  80582. this.diffuseTexture.dispose();
  80583. }
  80584. if (this.reflectionTexture) {
  80585. this.reflectionTexture.dispose();
  80586. }
  80587. }
  80588. this._renderTargets.dispose();
  80589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80591. }
  80592. _super.prototype.dispose.call(this, forceDisposeEffect);
  80593. };
  80594. /**
  80595. * Clones the material.
  80596. * @name The cloned name.
  80597. * @returns The cloned material.
  80598. */
  80599. BackgroundMaterial.prototype.clone = function (name) {
  80600. var _this = this;
  80601. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80602. };
  80603. /**
  80604. * Serializes the current material to its JSON representation.
  80605. * @returns The JSON representation.
  80606. */
  80607. BackgroundMaterial.prototype.serialize = function () {
  80608. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80609. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80610. return serializationObject;
  80611. };
  80612. /**
  80613. * Gets the class name of the material
  80614. * @returns "BackgroundMaterial"
  80615. */
  80616. BackgroundMaterial.prototype.getClassName = function () {
  80617. return "BackgroundMaterial";
  80618. };
  80619. /**
  80620. * Parse a JSON input to create back a background material.
  80621. * @param source
  80622. * @param scene
  80623. * @param rootUrl
  80624. * @returns the instantiated BackgroundMaterial.
  80625. */
  80626. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  80627. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  80628. };
  80629. /**
  80630. * Standard reflectance value at parallel view angle.
  80631. */
  80632. BackgroundMaterial.standardReflectance0 = 0.05;
  80633. /**
  80634. * Standard reflectance value at grazing angle.
  80635. */
  80636. BackgroundMaterial.standardReflectance90 = 0.5;
  80637. __decorate([
  80638. BABYLON.serializeAsColor3()
  80639. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  80640. __decorate([
  80641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80642. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  80643. __decorate([
  80644. BABYLON.serialize()
  80645. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  80646. __decorate([
  80647. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80648. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  80649. __decorate([
  80650. BABYLON.serializeAsColor3()
  80651. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  80652. __decorate([
  80653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80654. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  80655. __decorate([
  80656. BABYLON.serialize()
  80657. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  80658. __decorate([
  80659. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80660. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  80661. __decorate([
  80662. BABYLON.serializeAsColor3()
  80663. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  80664. __decorate([
  80665. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80666. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  80667. __decorate([
  80668. BABYLON.serialize()
  80669. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  80670. __decorate([
  80671. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80672. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  80673. __decorate([
  80674. BABYLON.serializeAsTexture()
  80675. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  80676. __decorate([
  80677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80678. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  80679. __decorate([
  80680. BABYLON.serialize()
  80681. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  80682. __decorate([
  80683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80684. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  80685. __decorate([
  80686. BABYLON.serializeAsTexture()
  80687. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  80688. __decorate([
  80689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80690. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  80691. __decorate([
  80692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80693. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  80694. __decorate([
  80695. BABYLON.serialize()
  80696. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  80697. __decorate([
  80698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80699. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  80700. __decorate([
  80701. BABYLON.serialize()
  80702. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  80703. __decorate([
  80704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80705. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  80706. __decorate([
  80707. BABYLON.serializeAsVector3()
  80708. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  80709. __decorate([
  80710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80711. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  80712. __decorate([
  80713. BABYLON.serialize()
  80714. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  80715. __decorate([
  80716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80717. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  80718. __decorate([
  80719. BABYLON.serialize()
  80720. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  80721. __decorate([
  80722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80723. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  80724. __decorate([
  80725. BABYLON.serialize()
  80726. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  80727. __decorate([
  80728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80729. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  80730. __decorate([
  80731. BABYLON.serialize()
  80732. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  80733. __decorate([
  80734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80735. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  80736. __decorate([
  80737. BABYLON.serialize()
  80738. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  80739. __decorate([
  80740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80741. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  80742. __decorate([
  80743. BABYLON.serialize()
  80744. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  80745. __decorate([
  80746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80747. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  80748. __decorate([
  80749. BABYLON.serialize()
  80750. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  80751. __decorate([
  80752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80753. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  80754. __decorate([
  80755. BABYLON.serialize()
  80756. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  80757. __decorate([
  80758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80759. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  80760. __decorate([
  80761. BABYLON.serialize()
  80762. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  80763. __decorate([
  80764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80765. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  80766. __decorate([
  80767. BABYLON.serializeAsImageProcessingConfiguration()
  80768. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  80769. return BackgroundMaterial;
  80770. }(BABYLON.PushMaterial));
  80771. BABYLON.BackgroundMaterial = BackgroundMaterial;
  80772. })(BABYLON || (BABYLON = {}));
  80773. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  80774. var __assign = (this && this.__assign) || Object.assign || function(t) {
  80775. for (var s, i = 1, n = arguments.length; i < n; i++) {
  80776. s = arguments[i];
  80777. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  80778. t[p] = s[p];
  80779. }
  80780. return t;
  80781. };
  80782. var BABYLON;
  80783. (function (BABYLON) {
  80784. /**
  80785. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  80786. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  80787. * It also helps with the default setup of your imageProcessing configuration.
  80788. */
  80789. var EnvironmentHelper = /** @class */ (function () {
  80790. /**
  80791. * constructor
  80792. * @param options
  80793. * @param scene The scene to add the material to
  80794. */
  80795. function EnvironmentHelper(options, scene) {
  80796. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  80797. this._scene = scene;
  80798. this._setupBackground();
  80799. this._setupImageProcessing();
  80800. }
  80801. /**
  80802. * Creates the default options for the helper.
  80803. */
  80804. EnvironmentHelper._getDefaultOptions = function () {
  80805. return {
  80806. createGround: true,
  80807. groundSize: 15,
  80808. groundTexture: this._groundTextureCDNUrl,
  80809. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80810. groundOpacity: 0.9,
  80811. enableGroundShadow: true,
  80812. groundShadowLevel: 0.5,
  80813. enableGroundMirror: false,
  80814. groundMirrorSizeRatio: 0.3,
  80815. groundMirrorBlurKernel: 64,
  80816. groundMirrorAmount: 1,
  80817. groundMirrorFresnelWeight: 1,
  80818. groundMirrorFallOffDistance: 0,
  80819. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  80820. groundYBias: 0.00001,
  80821. createSkybox: true,
  80822. skyboxSize: 20,
  80823. skyboxTexture: this._skyboxTextureCDNUrl,
  80824. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80825. backgroundYRotation: 0,
  80826. sizeAuto: true,
  80827. rootPosition: BABYLON.Vector3.Zero(),
  80828. setupImageProcessing: true,
  80829. environmentTexture: this._environmentTextureCDNUrl,
  80830. cameraExposure: 0.8,
  80831. cameraContrast: 1.2,
  80832. toneMappingEnabled: true,
  80833. };
  80834. };
  80835. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  80836. /**
  80837. * Gets the root mesh created by the helper.
  80838. */
  80839. get: function () {
  80840. return this._rootMesh;
  80841. },
  80842. enumerable: true,
  80843. configurable: true
  80844. });
  80845. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  80846. /**
  80847. * Gets the skybox created by the helper.
  80848. */
  80849. get: function () {
  80850. return this._skybox;
  80851. },
  80852. enumerable: true,
  80853. configurable: true
  80854. });
  80855. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  80856. /**
  80857. * Gets the skybox texture created by the helper.
  80858. */
  80859. get: function () {
  80860. return this._skyboxTexture;
  80861. },
  80862. enumerable: true,
  80863. configurable: true
  80864. });
  80865. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  80866. /**
  80867. * Gets the skybox material created by the helper.
  80868. */
  80869. get: function () {
  80870. return this._skyboxMaterial;
  80871. },
  80872. enumerable: true,
  80873. configurable: true
  80874. });
  80875. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  80876. /**
  80877. * Gets the ground mesh created by the helper.
  80878. */
  80879. get: function () {
  80880. return this._ground;
  80881. },
  80882. enumerable: true,
  80883. configurable: true
  80884. });
  80885. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  80886. /**
  80887. * Gets the ground texture created by the helper.
  80888. */
  80889. get: function () {
  80890. return this._groundTexture;
  80891. },
  80892. enumerable: true,
  80893. configurable: true
  80894. });
  80895. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  80896. /**
  80897. * Gets the ground mirror created by the helper.
  80898. */
  80899. get: function () {
  80900. return this._groundMirror;
  80901. },
  80902. enumerable: true,
  80903. configurable: true
  80904. });
  80905. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  80906. /**
  80907. * Gets the ground mirror render list to helps pushing the meshes
  80908. * you wish in the ground reflection.
  80909. */
  80910. get: function () {
  80911. if (this._groundMirror) {
  80912. return this._groundMirror.renderList;
  80913. }
  80914. return null;
  80915. },
  80916. enumerable: true,
  80917. configurable: true
  80918. });
  80919. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  80920. /**
  80921. * Gets the ground material created by the helper.
  80922. */
  80923. get: function () {
  80924. return this._groundMaterial;
  80925. },
  80926. enumerable: true,
  80927. configurable: true
  80928. });
  80929. /**
  80930. * Updates the background according to the new options
  80931. * @param options
  80932. */
  80933. EnvironmentHelper.prototype.updateOptions = function (options) {
  80934. var newOptions = __assign({}, this._options, options);
  80935. if (this._ground && !newOptions.createGround) {
  80936. this._ground.dispose();
  80937. this._ground = null;
  80938. }
  80939. if (this._groundMaterial && !newOptions.createGround) {
  80940. this._groundMaterial.dispose();
  80941. this._groundMaterial = null;
  80942. }
  80943. if (this._groundTexture) {
  80944. if (this._options.groundTexture != newOptions.groundTexture) {
  80945. this._groundTexture.dispose();
  80946. this._groundTexture = null;
  80947. }
  80948. }
  80949. if (this._skybox && !newOptions.createSkybox) {
  80950. this._skybox.dispose();
  80951. this._skybox = null;
  80952. }
  80953. if (this._skyboxMaterial && !newOptions.createSkybox) {
  80954. this._skyboxMaterial.dispose();
  80955. this._skyboxMaterial = null;
  80956. }
  80957. if (this._skyboxTexture) {
  80958. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  80959. this._skyboxTexture.dispose();
  80960. this._skyboxTexture = null;
  80961. }
  80962. }
  80963. if (this._groundMirror && !newOptions.enableGroundMirror) {
  80964. this._groundMirror.dispose();
  80965. this._groundMirror = null;
  80966. }
  80967. if (this._scene.environmentTexture) {
  80968. if (this._options.environmentTexture != newOptions.environmentTexture) {
  80969. this._scene.environmentTexture.dispose();
  80970. }
  80971. }
  80972. this._options = newOptions;
  80973. this._setupBackground();
  80974. this._setupImageProcessing();
  80975. };
  80976. /**
  80977. * Sets the primary color of all the available elements.
  80978. * @param color
  80979. */
  80980. EnvironmentHelper.prototype.setMainColor = function (color) {
  80981. if (this.groundMaterial) {
  80982. this.groundMaterial.primaryColor = color;
  80983. }
  80984. if (this.skyboxMaterial) {
  80985. this.skyboxMaterial.primaryColor = color;
  80986. }
  80987. if (this.groundMirror) {
  80988. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  80989. }
  80990. };
  80991. /**
  80992. * Setup the image processing according to the specified options.
  80993. */
  80994. EnvironmentHelper.prototype._setupImageProcessing = function () {
  80995. if (this._options.setupImageProcessing) {
  80996. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  80997. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  80998. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  80999. this._setupEnvironmentTexture();
  81000. }
  81001. };
  81002. /**
  81003. * Setup the environment texture according to the specified options.
  81004. */
  81005. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81006. if (this._scene.environmentTexture) {
  81007. return;
  81008. }
  81009. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81010. this._scene.environmentTexture = this._options.environmentTexture;
  81011. return;
  81012. }
  81013. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81014. this._scene.environmentTexture = environmentTexture;
  81015. };
  81016. /**
  81017. * Setup the background according to the specified options.
  81018. */
  81019. EnvironmentHelper.prototype._setupBackground = function () {
  81020. if (!this._rootMesh) {
  81021. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81022. }
  81023. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81024. var sceneSize = this._getSceneSize();
  81025. if (this._options.createGround) {
  81026. this._setupGround(sceneSize);
  81027. this._setupGroundMaterial();
  81028. this._setupGroundDiffuseTexture();
  81029. if (this._options.enableGroundMirror) {
  81030. this._setupGroundMirrorTexture(sceneSize);
  81031. }
  81032. this._setupMirrorInGroundMaterial();
  81033. }
  81034. if (this._options.createSkybox) {
  81035. this._setupSkybox(sceneSize);
  81036. this._setupSkyboxMaterial();
  81037. this._setupSkyboxReflectionTexture();
  81038. }
  81039. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81040. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81041. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81042. };
  81043. /**
  81044. * Get the scene sizes according to the setup.
  81045. */
  81046. EnvironmentHelper.prototype._getSceneSize = function () {
  81047. var groundSize = this._options.groundSize;
  81048. var skyboxSize = this._options.skyboxSize;
  81049. var rootPosition = this._options.rootPosition;
  81050. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81051. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81052. }
  81053. var sceneExtends = this._scene.getWorldExtends();
  81054. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81055. if (this._options.sizeAuto) {
  81056. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81057. this._scene.activeCamera.upperRadiusLimit) {
  81058. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81059. skyboxSize = groundSize;
  81060. }
  81061. var sceneDiagonalLenght = sceneDiagonal.length();
  81062. if (sceneDiagonalLenght > groundSize) {
  81063. groundSize = sceneDiagonalLenght * 2;
  81064. skyboxSize = groundSize;
  81065. }
  81066. // 10 % bigger.
  81067. groundSize *= 1.1;
  81068. skyboxSize *= 1.5;
  81069. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81070. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81071. }
  81072. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81073. };
  81074. /**
  81075. * Setup the ground according to the specified options.
  81076. */
  81077. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81078. var _this = this;
  81079. if (!this._ground) {
  81080. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81081. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81082. this._ground.parent = this._rootMesh;
  81083. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81084. }
  81085. this._ground.receiveShadows = this._options.enableGroundShadow;
  81086. };
  81087. /**
  81088. * Setup the ground material according to the specified options.
  81089. */
  81090. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81091. if (!this._groundMaterial) {
  81092. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81093. }
  81094. this._groundMaterial.alpha = this._options.groundOpacity;
  81095. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81096. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81097. this._groundMaterial.primaryLevel = 1;
  81098. this._groundMaterial.primaryColor = this._options.groundColor;
  81099. this._groundMaterial.secondaryLevel = 0;
  81100. this._groundMaterial.tertiaryLevel = 0;
  81101. this._groundMaterial.useRGBColor = false;
  81102. this._groundMaterial.enableNoise = true;
  81103. if (this._ground) {
  81104. this._ground.material = this._groundMaterial;
  81105. }
  81106. };
  81107. /**
  81108. * Setup the ground diffuse texture according to the specified options.
  81109. */
  81110. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81111. if (!this._groundMaterial) {
  81112. return;
  81113. }
  81114. if (this._groundTexture) {
  81115. return;
  81116. }
  81117. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81118. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81119. return;
  81120. }
  81121. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81122. diffuseTexture.gammaSpace = false;
  81123. diffuseTexture.hasAlpha = true;
  81124. this._groundMaterial.diffuseTexture = diffuseTexture;
  81125. };
  81126. /**
  81127. * Setup the ground mirror texture according to the specified options.
  81128. */
  81129. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81130. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81131. if (!this._groundMirror) {
  81132. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81133. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81134. this._groundMirror.anisotropicFilteringLevel = 1;
  81135. this._groundMirror.wrapU = wrapping;
  81136. this._groundMirror.wrapV = wrapping;
  81137. this._groundMirror.gammaSpace = false;
  81138. if (this._groundMirror.renderList) {
  81139. for (var i = 0; i < this._scene.meshes.length; i++) {
  81140. var mesh = this._scene.meshes[i];
  81141. if (mesh !== this._ground &&
  81142. mesh !== this._skybox &&
  81143. mesh !== this._rootMesh) {
  81144. this._groundMirror.renderList.push(mesh);
  81145. }
  81146. }
  81147. }
  81148. }
  81149. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81150. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81151. };
  81152. /**
  81153. * Setup the ground to receive the mirror texture.
  81154. */
  81155. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81156. if (this._groundMaterial) {
  81157. this._groundMaterial.reflectionTexture = this._groundMirror;
  81158. this._groundMaterial.reflectionFresnel = true;
  81159. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81160. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81161. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81162. }
  81163. };
  81164. /**
  81165. * Setup the skybox according to the specified options.
  81166. */
  81167. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81168. var _this = this;
  81169. if (!this._skybox) {
  81170. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81171. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81172. }
  81173. this._skybox.parent = this._rootMesh;
  81174. };
  81175. /**
  81176. * Setup the skybox material according to the specified options.
  81177. */
  81178. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81179. if (!this._skybox) {
  81180. return;
  81181. }
  81182. if (!this._skyboxMaterial) {
  81183. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81184. }
  81185. this._skyboxMaterial.useRGBColor = false;
  81186. this._skyboxMaterial.primaryLevel = 1;
  81187. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81188. this._skyboxMaterial.secondaryLevel = 0;
  81189. this._skyboxMaterial.tertiaryLevel = 0;
  81190. this._skyboxMaterial.enableNoise = true;
  81191. this._skybox.material = this._skyboxMaterial;
  81192. };
  81193. /**
  81194. * Setup the skybox reflection texture according to the specified options.
  81195. */
  81196. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81197. if (!this._skyboxMaterial) {
  81198. return;
  81199. }
  81200. if (this._skyboxTexture) {
  81201. return;
  81202. }
  81203. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81204. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81205. return;
  81206. }
  81207. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81208. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81209. this._skyboxTexture.gammaSpace = false;
  81210. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81211. };
  81212. /**
  81213. * Dispose all the elements created by the Helper.
  81214. */
  81215. EnvironmentHelper.prototype.dispose = function () {
  81216. if (this._groundMaterial) {
  81217. this._groundMaterial.dispose(true, true);
  81218. }
  81219. if (this._skyboxMaterial) {
  81220. this._skyboxMaterial.dispose(true, true);
  81221. }
  81222. this._rootMesh.dispose(false);
  81223. };
  81224. /**
  81225. * Default ground texture URL.
  81226. */
  81227. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81228. /**
  81229. * Default skybox texture URL.
  81230. */
  81231. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81232. /**
  81233. * Default environment texture URL.
  81234. */
  81235. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81236. return EnvironmentHelper;
  81237. }());
  81238. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81239. })(BABYLON || (BABYLON = {}));
  81240. //# sourceMappingURL=babylon.environmentHelper.js.map
  81241. 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=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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}"};
  81242. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  81243. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81244. var BABYLON;
  81245. (function (BABYLON) {
  81246. var GridMaterialDefines = /** @class */ (function (_super) {
  81247. __extends(GridMaterialDefines, _super);
  81248. function GridMaterialDefines() {
  81249. var _this = _super.call(this) || this;
  81250. _this.TRANSPARENT = false;
  81251. _this.FOG = false;
  81252. _this.PREMULTIPLYALPHA = false;
  81253. _this.rebuild();
  81254. return _this;
  81255. }
  81256. return GridMaterialDefines;
  81257. }(BABYLON.MaterialDefines));
  81258. /**
  81259. * The grid materials allows you to wrap any shape with a grid.
  81260. * Colors are customizable.
  81261. */
  81262. var GridMaterial = /** @class */ (function (_super) {
  81263. __extends(GridMaterial, _super);
  81264. /**
  81265. * constructor
  81266. * @param name The name given to the material in order to identify it afterwards.
  81267. * @param scene The scene the material is used in.
  81268. */
  81269. function GridMaterial(name, scene) {
  81270. var _this = _super.call(this, name, scene) || this;
  81271. /**
  81272. * Main color of the grid (e.g. between lines)
  81273. */
  81274. _this.mainColor = BABYLON.Color3.Black();
  81275. /**
  81276. * Color of the grid lines.
  81277. */
  81278. _this.lineColor = BABYLON.Color3.Teal();
  81279. /**
  81280. * The scale of the grid compared to unit.
  81281. */
  81282. _this.gridRatio = 1.0;
  81283. /**
  81284. * Allows setting an offset for the grid lines.
  81285. */
  81286. _this.gridOffset = BABYLON.Vector3.Zero();
  81287. /**
  81288. * The frequency of thicker lines.
  81289. */
  81290. _this.majorUnitFrequency = 10;
  81291. /**
  81292. * The visibility of minor units in the grid.
  81293. */
  81294. _this.minorUnitVisibility = 0.33;
  81295. /**
  81296. * The grid opacity outside of the lines.
  81297. */
  81298. _this.opacity = 1.0;
  81299. /**
  81300. * Determine RBG output is premultiplied by alpha value.
  81301. */
  81302. _this.preMultiplyAlpha = false;
  81303. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81304. return _this;
  81305. }
  81306. /**
  81307. * Returns wehter or not the grid requires alpha blending.
  81308. */
  81309. GridMaterial.prototype.needAlphaBlending = function () {
  81310. return this.opacity < 1.0;
  81311. };
  81312. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81313. return this.needAlphaBlending();
  81314. };
  81315. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81316. if (this.isFrozen) {
  81317. if (this._wasPreviouslyReady && subMesh.effect) {
  81318. return true;
  81319. }
  81320. }
  81321. if (!subMesh._materialDefines) {
  81322. subMesh._materialDefines = new GridMaterialDefines();
  81323. }
  81324. var defines = subMesh._materialDefines;
  81325. var scene = this.getScene();
  81326. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81327. if (this._renderId === scene.getRenderId()) {
  81328. return true;
  81329. }
  81330. }
  81331. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81332. defines.TRANSPARENT = !defines.TRANSPARENT;
  81333. defines.markAsUnprocessed();
  81334. }
  81335. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81336. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81337. defines.markAsUnprocessed();
  81338. }
  81339. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81340. // Get correct effect
  81341. if (defines.isDirty) {
  81342. defines.markAsProcessed();
  81343. scene.resetCachedMaterial();
  81344. // Attributes
  81345. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81346. // Defines
  81347. var join = defines.toString();
  81348. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81349. }
  81350. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81351. return false;
  81352. }
  81353. this._renderId = scene.getRenderId();
  81354. this._wasPreviouslyReady = true;
  81355. return true;
  81356. };
  81357. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81358. var scene = this.getScene();
  81359. var defines = subMesh._materialDefines;
  81360. if (!defines) {
  81361. return;
  81362. }
  81363. var effect = subMesh.effect;
  81364. if (!effect) {
  81365. return;
  81366. }
  81367. this._activeEffect = effect;
  81368. // Matrices
  81369. this.bindOnlyWorldMatrix(world);
  81370. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81371. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81372. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81373. // Uniforms
  81374. if (this._mustRebind(scene, effect)) {
  81375. this._activeEffect.setColor3("mainColor", this.mainColor);
  81376. this._activeEffect.setColor3("lineColor", this.lineColor);
  81377. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81378. this._gridControl.x = this.gridRatio;
  81379. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81380. this._gridControl.z = this.minorUnitVisibility;
  81381. this._gridControl.w = this.opacity;
  81382. this._activeEffect.setVector4("gridControl", this._gridControl);
  81383. }
  81384. // Fog
  81385. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81386. this._afterBind(mesh, this._activeEffect);
  81387. };
  81388. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81389. _super.prototype.dispose.call(this, forceDisposeEffect);
  81390. };
  81391. GridMaterial.prototype.clone = function (name) {
  81392. var _this = this;
  81393. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81394. };
  81395. GridMaterial.prototype.serialize = function () {
  81396. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81397. serializationObject.customType = "BABYLON.GridMaterial";
  81398. return serializationObject;
  81399. };
  81400. GridMaterial.prototype.getClassName = function () {
  81401. return "GridMaterial";
  81402. };
  81403. GridMaterial.Parse = function (source, scene, rootUrl) {
  81404. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81405. };
  81406. __decorate([
  81407. BABYLON.serializeAsColor3()
  81408. ], GridMaterial.prototype, "mainColor", void 0);
  81409. __decorate([
  81410. BABYLON.serializeAsColor3()
  81411. ], GridMaterial.prototype, "lineColor", void 0);
  81412. __decorate([
  81413. BABYLON.serialize()
  81414. ], GridMaterial.prototype, "gridRatio", void 0);
  81415. __decorate([
  81416. BABYLON.serializeAsColor3()
  81417. ], GridMaterial.prototype, "gridOffset", void 0);
  81418. __decorate([
  81419. BABYLON.serialize()
  81420. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81421. __decorate([
  81422. BABYLON.serialize()
  81423. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81424. __decorate([
  81425. BABYLON.serialize()
  81426. ], GridMaterial.prototype, "opacity", void 0);
  81427. __decorate([
  81428. BABYLON.serialize()
  81429. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81430. return GridMaterial;
  81431. }(BABYLON.PushMaterial));
  81432. BABYLON.GridMaterial = GridMaterial;
  81433. })(BABYLON || (BABYLON = {}));
  81434. //# sourceMappingURL=babylon.gridmaterial.js.map
  81435. 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}";
  81436. 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}";
  81437. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81438. var BABYLON;
  81439. (function (BABYLON) {
  81440. var GLTFLoaderCoordinateSystemMode;
  81441. (function (GLTFLoaderCoordinateSystemMode) {
  81442. /**
  81443. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81444. */
  81445. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81446. /**
  81447. * Sets the useRightHandedSystem flag on the scene.
  81448. */
  81449. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81450. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81451. var GLTFLoaderAnimationStartMode;
  81452. (function (GLTFLoaderAnimationStartMode) {
  81453. /**
  81454. * No animation will start.
  81455. */
  81456. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81457. /**
  81458. * The first animation will start.
  81459. */
  81460. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81461. /**
  81462. * All animations will start.
  81463. */
  81464. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  81465. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  81466. var GLTFFileLoader = /** @class */ (function () {
  81467. function GLTFFileLoader() {
  81468. // #region Common options
  81469. /**
  81470. * Raised when the asset has been parsed.
  81471. * The data.json property stores the glTF JSON.
  81472. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  81473. */
  81474. this.onParsedObservable = new BABYLON.Observable();
  81475. // #endregion
  81476. // #region V2 options
  81477. /**
  81478. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  81479. */
  81480. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  81481. /**
  81482. * The animation start mode (NONE, FIRST, ALL).
  81483. */
  81484. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  81485. /**
  81486. * Set to true to compile materials before raising the success callback.
  81487. */
  81488. this.compileMaterials = false;
  81489. /**
  81490. * Set to true to also compile materials with clip planes.
  81491. */
  81492. this.useClipPlane = false;
  81493. /**
  81494. * Set to true to compile shadow generators before raising the success callback.
  81495. */
  81496. this.compileShadowGenerators = false;
  81497. /**
  81498. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  81499. */
  81500. this.onMeshLoadedObservable = new BABYLON.Observable();
  81501. /**
  81502. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  81503. */
  81504. this.onTextureLoadedObservable = new BABYLON.Observable();
  81505. /**
  81506. * Raised when the loader creates a material after parsing the glTF properties of the material.
  81507. */
  81508. this.onMaterialLoadedObservable = new BABYLON.Observable();
  81509. /**
  81510. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81511. * For assets with LODs, raised when all of the LODs are complete.
  81512. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  81513. */
  81514. this.onCompleteObservable = new BABYLON.Observable();
  81515. /**
  81516. * Raised when the loader is disposed.
  81517. */
  81518. this.onDisposeObservable = new BABYLON.Observable();
  81519. // #endregion
  81520. this._loader = null;
  81521. this.name = "gltf";
  81522. this.extensions = {
  81523. ".gltf": { isBinary: false },
  81524. ".glb": { isBinary: true }
  81525. };
  81526. }
  81527. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  81528. set: function (callback) {
  81529. if (this._onParsedObserver) {
  81530. this.onParsedObservable.remove(this._onParsedObserver);
  81531. }
  81532. this._onParsedObserver = this.onParsedObservable.add(callback);
  81533. },
  81534. enumerable: true,
  81535. configurable: true
  81536. });
  81537. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  81538. set: function (callback) {
  81539. if (this._onMeshLoadedObserver) {
  81540. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  81541. }
  81542. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  81543. },
  81544. enumerable: true,
  81545. configurable: true
  81546. });
  81547. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  81548. set: function (callback) {
  81549. if (this._onTextureLoadedObserver) {
  81550. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  81551. }
  81552. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  81553. },
  81554. enumerable: true,
  81555. configurable: true
  81556. });
  81557. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  81558. set: function (callback) {
  81559. if (this._onMaterialLoadedObserver) {
  81560. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  81561. }
  81562. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  81563. },
  81564. enumerable: true,
  81565. configurable: true
  81566. });
  81567. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  81568. set: function (callback) {
  81569. if (this._onCompleteObserver) {
  81570. this.onCompleteObservable.remove(this._onCompleteObserver);
  81571. }
  81572. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  81573. },
  81574. enumerable: true,
  81575. configurable: true
  81576. });
  81577. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  81578. set: function (callback) {
  81579. if (this._onDisposeObserver) {
  81580. this.onDisposeObservable.remove(this._onDisposeObserver);
  81581. }
  81582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81583. },
  81584. enumerable: true,
  81585. configurable: true
  81586. });
  81587. /**
  81588. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  81589. */
  81590. GLTFFileLoader.prototype.dispose = function () {
  81591. if (this._loader) {
  81592. this._loader.dispose();
  81593. this._loader = null;
  81594. }
  81595. this.onParsedObservable.clear();
  81596. this.onMeshLoadedObservable.clear();
  81597. this.onTextureLoadedObservable.clear();
  81598. this.onMaterialLoadedObservable.clear();
  81599. this.onCompleteObservable.clear();
  81600. this.onDisposeObservable.notifyObservers(this);
  81601. this.onDisposeObservable.clear();
  81602. };
  81603. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81604. try {
  81605. var loaderData = this._parse(data);
  81606. this._loader = this._getLoader(loaderData);
  81607. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  81608. }
  81609. catch (e) {
  81610. if (onError) {
  81611. onError(e.message, e);
  81612. }
  81613. else {
  81614. BABYLON.Tools.Error(e.message);
  81615. }
  81616. }
  81617. };
  81618. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81619. try {
  81620. var loaderData = this._parse(data);
  81621. this._loader = this._getLoader(loaderData);
  81622. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  81623. }
  81624. catch (e) {
  81625. if (onError) {
  81626. onError(e.message, e);
  81627. }
  81628. else {
  81629. BABYLON.Tools.Error(e.message);
  81630. }
  81631. }
  81632. };
  81633. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81634. try {
  81635. var loaderData = this._parse(data);
  81636. this._loader = this._getLoader(loaderData);
  81637. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  81638. var container = new BABYLON.AssetContainer(scene);
  81639. Array.prototype.push.apply(container.meshes, meshes);
  81640. Array.prototype.push.apply(container.particleSystems, particleSystems);
  81641. Array.prototype.push.apply(container.skeletons, skeletons);
  81642. container.removeAllFromScene();
  81643. onSuccess(container);
  81644. }, onProgress, onError);
  81645. }
  81646. catch (e) {
  81647. if (onError) {
  81648. onError(e.message, e);
  81649. }
  81650. else {
  81651. BABYLON.Tools.Error(e.message);
  81652. }
  81653. }
  81654. };
  81655. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  81656. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  81657. };
  81658. GLTFFileLoader.prototype.createPlugin = function () {
  81659. return new GLTFFileLoader();
  81660. };
  81661. GLTFFileLoader.prototype._parse = function (data) {
  81662. var parsedData;
  81663. if (data instanceof ArrayBuffer) {
  81664. parsedData = GLTFFileLoader._parseBinary(data);
  81665. }
  81666. else {
  81667. parsedData = {
  81668. json: JSON.parse(data),
  81669. bin: null
  81670. };
  81671. }
  81672. this.onParsedObservable.notifyObservers(parsedData);
  81673. return parsedData;
  81674. };
  81675. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  81676. var _this = this;
  81677. var loaderVersion = { major: 2, minor: 0 };
  81678. var asset = loaderData.json.asset || {};
  81679. var version = GLTFFileLoader._parseVersion(asset.version);
  81680. if (!version) {
  81681. throw new Error("Invalid version: " + asset.version);
  81682. }
  81683. if (asset.minVersion !== undefined) {
  81684. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  81685. if (!minVersion) {
  81686. throw new Error("Invalid minimum version: " + asset.minVersion);
  81687. }
  81688. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  81689. throw new Error("Incompatible minimum version: " + asset.minVersion);
  81690. }
  81691. }
  81692. var createLoaders = {
  81693. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  81694. 2: GLTFFileLoader.CreateGLTFLoaderV2
  81695. };
  81696. var createLoader = createLoaders[version.major];
  81697. if (!createLoader) {
  81698. throw new Error("Unsupported version: " + asset.version);
  81699. }
  81700. var loader = createLoader();
  81701. loader.coordinateSystemMode = this.coordinateSystemMode;
  81702. loader.animationStartMode = this.animationStartMode;
  81703. loader.compileMaterials = this.compileMaterials;
  81704. loader.useClipPlane = this.useClipPlane;
  81705. loader.compileShadowGenerators = this.compileShadowGenerators;
  81706. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  81707. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  81708. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  81709. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  81710. return loader;
  81711. };
  81712. GLTFFileLoader._parseBinary = function (data) {
  81713. var Binary = {
  81714. Magic: 0x46546C67
  81715. };
  81716. var binaryReader = new BinaryReader(data);
  81717. var magic = binaryReader.readUint32();
  81718. if (magic !== Binary.Magic) {
  81719. throw new Error("Unexpected magic: " + magic);
  81720. }
  81721. var version = binaryReader.readUint32();
  81722. switch (version) {
  81723. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81724. case 2: return GLTFFileLoader._parseV2(binaryReader);
  81725. }
  81726. throw new Error("Unsupported version: " + version);
  81727. };
  81728. GLTFFileLoader._parseV1 = function (binaryReader) {
  81729. var ContentFormat = {
  81730. JSON: 0
  81731. };
  81732. var length = binaryReader.readUint32();
  81733. if (length != binaryReader.getLength()) {
  81734. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  81735. }
  81736. var contentLength = binaryReader.readUint32();
  81737. var contentFormat = binaryReader.readUint32();
  81738. var content;
  81739. switch (contentFormat) {
  81740. case ContentFormat.JSON: {
  81741. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  81742. break;
  81743. }
  81744. default: {
  81745. throw new Error("Unexpected content format: " + contentFormat);
  81746. }
  81747. }
  81748. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  81749. var body = binaryReader.readUint8Array(bytesRemaining);
  81750. return {
  81751. json: content,
  81752. bin: body
  81753. };
  81754. };
  81755. GLTFFileLoader._parseV2 = function (binaryReader) {
  81756. var ChunkFormat = {
  81757. JSON: 0x4E4F534A,
  81758. BIN: 0x004E4942
  81759. };
  81760. var length = binaryReader.readUint32();
  81761. if (length !== binaryReader.getLength()) {
  81762. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  81763. }
  81764. // JSON chunk
  81765. var chunkLength = binaryReader.readUint32();
  81766. var chunkFormat = binaryReader.readUint32();
  81767. if (chunkFormat !== ChunkFormat.JSON) {
  81768. throw new Error("First chunk format is not JSON");
  81769. }
  81770. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  81771. // Look for BIN chunk
  81772. var bin = null;
  81773. while (binaryReader.getPosition() < binaryReader.getLength()) {
  81774. var chunkLength_1 = binaryReader.readUint32();
  81775. var chunkFormat_1 = binaryReader.readUint32();
  81776. switch (chunkFormat_1) {
  81777. case ChunkFormat.JSON: {
  81778. throw new Error("Unexpected JSON chunk");
  81779. }
  81780. case ChunkFormat.BIN: {
  81781. bin = binaryReader.readUint8Array(chunkLength_1);
  81782. break;
  81783. }
  81784. default: {
  81785. // ignore unrecognized chunkFormat
  81786. binaryReader.skipBytes(chunkLength_1);
  81787. break;
  81788. }
  81789. }
  81790. }
  81791. return {
  81792. json: json,
  81793. bin: bin
  81794. };
  81795. };
  81796. GLTFFileLoader._parseVersion = function (version) {
  81797. if (version === "1.0" || version === "1.0.1") {
  81798. return {
  81799. major: 1,
  81800. minor: 0
  81801. };
  81802. }
  81803. var match = (version + "").match(/^(\d+)\.(\d+)/);
  81804. if (!match) {
  81805. return null;
  81806. }
  81807. return {
  81808. major: parseInt(match[1]),
  81809. minor: parseInt(match[2])
  81810. };
  81811. };
  81812. GLTFFileLoader._compareVersion = function (a, b) {
  81813. if (a.major > b.major)
  81814. return 1;
  81815. if (a.major < b.major)
  81816. return -1;
  81817. if (a.minor > b.minor)
  81818. return 1;
  81819. if (a.minor < b.minor)
  81820. return -1;
  81821. return 0;
  81822. };
  81823. GLTFFileLoader._decodeBufferToText = function (buffer) {
  81824. var result = "";
  81825. var length = buffer.byteLength;
  81826. for (var i = 0; i < length; i++) {
  81827. result += String.fromCharCode(buffer[i]);
  81828. }
  81829. return result;
  81830. };
  81831. // #endregion
  81832. // #region V1 options
  81833. GLTFFileLoader.IncrementalLoading = true;
  81834. GLTFFileLoader.HomogeneousCoordinates = false;
  81835. return GLTFFileLoader;
  81836. }());
  81837. BABYLON.GLTFFileLoader = GLTFFileLoader;
  81838. var BinaryReader = /** @class */ (function () {
  81839. function BinaryReader(arrayBuffer) {
  81840. this._arrayBuffer = arrayBuffer;
  81841. this._dataView = new DataView(arrayBuffer);
  81842. this._byteOffset = 0;
  81843. }
  81844. BinaryReader.prototype.getPosition = function () {
  81845. return this._byteOffset;
  81846. };
  81847. BinaryReader.prototype.getLength = function () {
  81848. return this._arrayBuffer.byteLength;
  81849. };
  81850. BinaryReader.prototype.readUint32 = function () {
  81851. var value = this._dataView.getUint32(this._byteOffset, true);
  81852. this._byteOffset += 4;
  81853. return value;
  81854. };
  81855. BinaryReader.prototype.readUint8Array = function (length) {
  81856. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  81857. this._byteOffset += length;
  81858. return value;
  81859. };
  81860. BinaryReader.prototype.skipBytes = function (length) {
  81861. this._byteOffset += length;
  81862. };
  81863. return BinaryReader;
  81864. }());
  81865. if (BABYLON.SceneLoader) {
  81866. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  81867. }
  81868. })(BABYLON || (BABYLON = {}));
  81869. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  81870. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81871. var BABYLON;
  81872. (function (BABYLON) {
  81873. var GLTF1;
  81874. (function (GLTF1) {
  81875. /**
  81876. * Enums
  81877. */
  81878. var EComponentType;
  81879. (function (EComponentType) {
  81880. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  81881. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  81882. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  81883. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  81884. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  81885. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  81886. var EShaderType;
  81887. (function (EShaderType) {
  81888. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  81889. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  81890. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  81891. var EParameterType;
  81892. (function (EParameterType) {
  81893. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  81894. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  81895. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  81896. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  81897. EParameterType[EParameterType["INT"] = 5124] = "INT";
  81898. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  81899. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  81900. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  81901. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  81902. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  81903. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  81904. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  81905. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  81906. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  81907. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  81908. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  81909. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  81910. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  81911. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  81912. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  81913. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  81914. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  81915. var ETextureWrapMode;
  81916. (function (ETextureWrapMode) {
  81917. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  81918. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  81919. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  81920. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  81921. var ETextureFilterType;
  81922. (function (ETextureFilterType) {
  81923. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  81924. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  81925. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  81926. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  81927. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  81928. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  81929. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  81930. var ETextureFormat;
  81931. (function (ETextureFormat) {
  81932. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  81933. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  81934. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  81935. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  81936. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  81937. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  81938. var ECullingType;
  81939. (function (ECullingType) {
  81940. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  81941. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  81942. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  81943. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  81944. var EBlendingFunction;
  81945. (function (EBlendingFunction) {
  81946. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  81947. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  81948. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  81949. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  81950. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  81951. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  81952. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  81953. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  81954. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  81955. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  81956. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  81957. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  81958. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  81959. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  81960. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  81961. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  81962. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81963. })(BABYLON || (BABYLON = {}));
  81964. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  81965. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81966. var BABYLON;
  81967. (function (BABYLON) {
  81968. var GLTF1;
  81969. (function (GLTF1) {
  81970. /**
  81971. * Tokenizer. Used for shaders compatibility
  81972. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  81973. */
  81974. var ETokenType;
  81975. (function (ETokenType) {
  81976. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  81977. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  81978. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  81979. })(ETokenType || (ETokenType = {}));
  81980. var Tokenizer = /** @class */ (function () {
  81981. function Tokenizer(toParse) {
  81982. this._pos = 0;
  81983. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  81984. this._toParse = toParse;
  81985. this._maxPos = toParse.length;
  81986. }
  81987. Tokenizer.prototype.getNextToken = function () {
  81988. if (this.isEnd())
  81989. return ETokenType.END_OF_INPUT;
  81990. this.currentString = this.read();
  81991. this.currentToken = ETokenType.UNKNOWN;
  81992. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  81993. this.currentToken = ETokenType.IDENTIFIER;
  81994. this.currentIdentifier = this.currentString;
  81995. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  81996. this.currentIdentifier += this.currentString;
  81997. this.forward();
  81998. }
  81999. }
  82000. return this.currentToken;
  82001. };
  82002. Tokenizer.prototype.peek = function () {
  82003. return this._toParse[this._pos];
  82004. };
  82005. Tokenizer.prototype.read = function () {
  82006. return this._toParse[this._pos++];
  82007. };
  82008. Tokenizer.prototype.forward = function () {
  82009. this._pos++;
  82010. };
  82011. Tokenizer.prototype.isEnd = function () {
  82012. return this._pos >= this._maxPos;
  82013. };
  82014. return Tokenizer;
  82015. }());
  82016. /**
  82017. * Values
  82018. */
  82019. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82020. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82021. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82022. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82023. /**
  82024. * Parse
  82025. */
  82026. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82027. for (var buf in parsedBuffers) {
  82028. var parsedBuffer = parsedBuffers[buf];
  82029. gltfRuntime.buffers[buf] = parsedBuffer;
  82030. gltfRuntime.buffersCount++;
  82031. }
  82032. };
  82033. var parseShaders = function (parsedShaders, gltfRuntime) {
  82034. for (var sha in parsedShaders) {
  82035. var parsedShader = parsedShaders[sha];
  82036. gltfRuntime.shaders[sha] = parsedShader;
  82037. gltfRuntime.shaderscount++;
  82038. }
  82039. };
  82040. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82041. for (var object in parsedObjects) {
  82042. var parsedObject = parsedObjects[object];
  82043. gltfRuntime[runtimeProperty][object] = parsedObject;
  82044. }
  82045. };
  82046. /**
  82047. * Utils
  82048. */
  82049. var normalizeUVs = function (buffer) {
  82050. if (!buffer) {
  82051. return;
  82052. }
  82053. for (var i = 0; i < buffer.length / 2; i++) {
  82054. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82055. }
  82056. };
  82057. var getAttribute = function (attributeParameter) {
  82058. if (attributeParameter.semantic === "NORMAL") {
  82059. return "normal";
  82060. }
  82061. else if (attributeParameter.semantic === "POSITION") {
  82062. return "position";
  82063. }
  82064. else if (attributeParameter.semantic === "JOINT") {
  82065. return "matricesIndices";
  82066. }
  82067. else if (attributeParameter.semantic === "WEIGHT") {
  82068. return "matricesWeights";
  82069. }
  82070. else if (attributeParameter.semantic === "COLOR") {
  82071. return "color";
  82072. }
  82073. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82074. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82075. return "uv" + (channel === 0 ? "" : channel + 1);
  82076. }
  82077. return null;
  82078. };
  82079. /**
  82080. * Loads and creates animations
  82081. */
  82082. var loadAnimations = function (gltfRuntime) {
  82083. for (var anim in gltfRuntime.animations) {
  82084. var animation = gltfRuntime.animations[anim];
  82085. if (!animation.channels || !animation.samplers) {
  82086. continue;
  82087. }
  82088. var lastAnimation = null;
  82089. for (var i = 0; i < animation.channels.length; i++) {
  82090. // Get parameters and load buffers
  82091. var channel = animation.channels[i];
  82092. var sampler = animation.samplers[channel.sampler];
  82093. if (!sampler) {
  82094. continue;
  82095. }
  82096. var inputData = null;
  82097. var outputData = null;
  82098. if (animation.parameters) {
  82099. inputData = animation.parameters[sampler.input];
  82100. outputData = animation.parameters[sampler.output];
  82101. }
  82102. else {
  82103. inputData = sampler.input;
  82104. outputData = sampler.output;
  82105. }
  82106. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82107. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82108. var targetID = channel.target.id;
  82109. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82110. if (targetNode === null) {
  82111. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82112. }
  82113. if (targetNode === null) {
  82114. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82115. continue;
  82116. }
  82117. var isBone = targetNode instanceof BABYLON.Bone;
  82118. // Get target path (position, rotation or scaling)
  82119. var targetPath = channel.target.path;
  82120. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82121. if (targetPathIndex !== -1) {
  82122. targetPath = babylonAnimationPaths[targetPathIndex];
  82123. }
  82124. // Determine animation type
  82125. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82126. if (!isBone) {
  82127. if (targetPath === "rotationQuaternion") {
  82128. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82129. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82130. }
  82131. else {
  82132. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82133. }
  82134. }
  82135. // Create animation and key frames
  82136. var babylonAnimation = null;
  82137. var keys = [];
  82138. var arrayOffset = 0;
  82139. var modifyKey = false;
  82140. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82141. babylonAnimation = lastAnimation;
  82142. modifyKey = true;
  82143. }
  82144. if (!modifyKey) {
  82145. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82146. }
  82147. // For each frame
  82148. for (var j = 0; j < bufferInput.length; j++) {
  82149. var value = null;
  82150. if (targetPath === "rotationQuaternion") {
  82151. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82152. arrayOffset += 4;
  82153. }
  82154. else {
  82155. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82156. arrayOffset += 3;
  82157. }
  82158. if (isBone) {
  82159. var bone = targetNode;
  82160. var translation = BABYLON.Vector3.Zero();
  82161. var rotationQuaternion = new BABYLON.Quaternion();
  82162. var scaling = BABYLON.Vector3.Zero();
  82163. // Warning on decompose
  82164. var mat = bone.getBaseMatrix();
  82165. if (modifyKey && lastAnimation) {
  82166. mat = lastAnimation.getKeys()[j].value;
  82167. }
  82168. mat.decompose(scaling, rotationQuaternion, translation);
  82169. if (targetPath === "position") {
  82170. translation = value;
  82171. }
  82172. else if (targetPath === "rotationQuaternion") {
  82173. rotationQuaternion = value;
  82174. }
  82175. else {
  82176. scaling = value;
  82177. }
  82178. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82179. }
  82180. if (!modifyKey) {
  82181. keys.push({
  82182. frame: bufferInput[j],
  82183. value: value
  82184. });
  82185. }
  82186. else if (lastAnimation) {
  82187. lastAnimation.getKeys()[j].value = value;
  82188. }
  82189. }
  82190. // Finish
  82191. if (!modifyKey && babylonAnimation) {
  82192. babylonAnimation.setKeys(keys);
  82193. targetNode.animations.push(babylonAnimation);
  82194. }
  82195. lastAnimation = babylonAnimation;
  82196. gltfRuntime.scene.stopAnimation(targetNode);
  82197. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82198. }
  82199. }
  82200. };
  82201. /**
  82202. * Returns the bones transformation matrix
  82203. */
  82204. var configureBoneTransformation = function (node) {
  82205. var mat = null;
  82206. if (node.translation || node.rotation || node.scale) {
  82207. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82208. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82209. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82210. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82211. }
  82212. else {
  82213. mat = BABYLON.Matrix.FromArray(node.matrix);
  82214. }
  82215. return mat;
  82216. };
  82217. /**
  82218. * Returns the parent bone
  82219. */
  82220. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82221. // Try to find
  82222. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82223. if (newSkeleton.bones[i].name === jointName) {
  82224. return newSkeleton.bones[i];
  82225. }
  82226. }
  82227. // Not found, search in gltf nodes
  82228. var nodes = gltfRuntime.nodes;
  82229. for (var nde in nodes) {
  82230. var node = nodes[nde];
  82231. if (!node.jointName) {
  82232. continue;
  82233. }
  82234. var children = node.children;
  82235. for (var i = 0; i < children.length; i++) {
  82236. var child = gltfRuntime.nodes[children[i]];
  82237. if (!child.jointName) {
  82238. continue;
  82239. }
  82240. if (child.jointName === jointName) {
  82241. var mat = configureBoneTransformation(node);
  82242. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82243. bone.id = nde;
  82244. return bone;
  82245. }
  82246. }
  82247. }
  82248. return null;
  82249. };
  82250. /**
  82251. * Returns the appropriate root node
  82252. */
  82253. var getNodeToRoot = function (nodesToRoot, id) {
  82254. for (var i = 0; i < nodesToRoot.length; i++) {
  82255. var nodeToRoot = nodesToRoot[i];
  82256. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82257. var child = nodeToRoot.node.children[j];
  82258. if (child === id) {
  82259. return nodeToRoot.bone;
  82260. }
  82261. }
  82262. }
  82263. return null;
  82264. };
  82265. /**
  82266. * Returns the node with the joint name
  82267. */
  82268. var getJointNode = function (gltfRuntime, jointName) {
  82269. var nodes = gltfRuntime.nodes;
  82270. var node = nodes[jointName];
  82271. if (node) {
  82272. return {
  82273. node: node,
  82274. id: jointName
  82275. };
  82276. }
  82277. for (var nde in nodes) {
  82278. node = nodes[nde];
  82279. if (node.jointName === jointName) {
  82280. return {
  82281. node: node,
  82282. id: nde
  82283. };
  82284. }
  82285. }
  82286. return null;
  82287. };
  82288. /**
  82289. * Checks if a nodes is in joints
  82290. */
  82291. var nodeIsInJoints = function (skins, id) {
  82292. for (var i = 0; i < skins.jointNames.length; i++) {
  82293. if (skins.jointNames[i] === id) {
  82294. return true;
  82295. }
  82296. }
  82297. return false;
  82298. };
  82299. /**
  82300. * Fills the nodes to root for bones and builds hierarchy
  82301. */
  82302. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82303. // Creates nodes for root
  82304. for (var nde in gltfRuntime.nodes) {
  82305. var node = gltfRuntime.nodes[nde];
  82306. var id = nde;
  82307. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82308. continue;
  82309. }
  82310. // Create node to root bone
  82311. var mat = configureBoneTransformation(node);
  82312. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82313. bone.id = id;
  82314. nodesToRoot.push({ bone: bone, node: node, id: id });
  82315. }
  82316. // Parenting
  82317. for (var i = 0; i < nodesToRoot.length; i++) {
  82318. var nodeToRoot = nodesToRoot[i];
  82319. var children = nodeToRoot.node.children;
  82320. for (var j = 0; j < children.length; j++) {
  82321. var child = null;
  82322. for (var k = 0; k < nodesToRoot.length; k++) {
  82323. if (nodesToRoot[k].id === children[j]) {
  82324. child = nodesToRoot[k];
  82325. break;
  82326. }
  82327. }
  82328. if (child) {
  82329. child.bone._parent = nodeToRoot.bone;
  82330. nodeToRoot.bone.children.push(child.bone);
  82331. }
  82332. }
  82333. }
  82334. };
  82335. /**
  82336. * Imports a skeleton
  82337. */
  82338. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82339. if (!newSkeleton) {
  82340. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82341. }
  82342. if (!skins.babylonSkeleton) {
  82343. return newSkeleton;
  82344. }
  82345. // Find the root bones
  82346. var nodesToRoot = [];
  82347. var nodesToRootToAdd = [];
  82348. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82349. newSkeleton.bones = [];
  82350. // Joints
  82351. for (var i = 0; i < skins.jointNames.length; i++) {
  82352. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82353. if (!jointNode) {
  82354. continue;
  82355. }
  82356. var node = jointNode.node;
  82357. if (!node) {
  82358. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82359. continue;
  82360. }
  82361. var id = jointNode.id;
  82362. // Optimize, if the bone already exists...
  82363. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82364. if (existingBone) {
  82365. newSkeleton.bones.push(existingBone);
  82366. continue;
  82367. }
  82368. // Search for parent bone
  82369. var foundBone = false;
  82370. var parentBone = null;
  82371. for (var j = 0; j < i; j++) {
  82372. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82373. if (!jointNode_1) {
  82374. continue;
  82375. }
  82376. var joint = jointNode_1.node;
  82377. if (!joint) {
  82378. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82379. continue;
  82380. }
  82381. var children = joint.children;
  82382. if (!children) {
  82383. continue;
  82384. }
  82385. foundBone = false;
  82386. for (var k = 0; k < children.length; k++) {
  82387. if (children[k] === id) {
  82388. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82389. foundBone = true;
  82390. break;
  82391. }
  82392. }
  82393. if (foundBone) {
  82394. break;
  82395. }
  82396. }
  82397. // Create bone
  82398. var mat = configureBoneTransformation(node);
  82399. if (!parentBone && nodesToRoot.length > 0) {
  82400. parentBone = getNodeToRoot(nodesToRoot, id);
  82401. if (parentBone) {
  82402. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82403. nodesToRootToAdd.push(parentBone);
  82404. }
  82405. }
  82406. }
  82407. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82408. bone.id = id;
  82409. }
  82410. // Polish
  82411. var bones = newSkeleton.bones;
  82412. newSkeleton.bones = [];
  82413. for (var i = 0; i < skins.jointNames.length; i++) {
  82414. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82415. if (!jointNode) {
  82416. continue;
  82417. }
  82418. for (var j = 0; j < bones.length; j++) {
  82419. if (bones[j].id === jointNode.id) {
  82420. newSkeleton.bones.push(bones[j]);
  82421. break;
  82422. }
  82423. }
  82424. }
  82425. newSkeleton.prepare();
  82426. // Finish
  82427. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82428. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82429. }
  82430. return newSkeleton;
  82431. };
  82432. /**
  82433. * Imports a mesh and its geometries
  82434. */
  82435. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82436. if (!newMesh) {
  82437. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82438. newMesh.id = id;
  82439. }
  82440. if (!node.babylonNode) {
  82441. return newMesh;
  82442. }
  82443. var subMaterials = [];
  82444. var vertexData = new BABYLON.VertexData();
  82445. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82446. var verticesStarts = new Array();
  82447. var verticesCounts = new Array();
  82448. var indexStarts = new Array();
  82449. var indexCounts = new Array();
  82450. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82451. var meshID = meshes[meshIndex];
  82452. var mesh = gltfRuntime.meshes[meshID];
  82453. if (!mesh) {
  82454. continue;
  82455. }
  82456. // Positions, normals and UVs
  82457. for (var i = 0; i < mesh.primitives.length; i++) {
  82458. // Temporary vertex data
  82459. var tempVertexData = new BABYLON.VertexData();
  82460. var primitive = mesh.primitives[i];
  82461. if (primitive.mode !== 4) {
  82462. // continue;
  82463. }
  82464. var attributes = primitive.attributes;
  82465. var accessor = null;
  82466. var buffer = null;
  82467. // Set positions, normal and uvs
  82468. for (var semantic in attributes) {
  82469. // Link accessor and buffer view
  82470. accessor = gltfRuntime.accessors[attributes[semantic]];
  82471. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82472. if (semantic === "NORMAL") {
  82473. tempVertexData.normals = new Float32Array(buffer.length);
  82474. tempVertexData.normals.set(buffer);
  82475. }
  82476. else if (semantic === "POSITION") {
  82477. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  82478. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  82479. for (var j = 0; j < buffer.length; j += 4) {
  82480. tempVertexData.positions[j] = buffer[j];
  82481. tempVertexData.positions[j + 1] = buffer[j + 1];
  82482. tempVertexData.positions[j + 2] = buffer[j + 2];
  82483. }
  82484. }
  82485. else {
  82486. tempVertexData.positions = new Float32Array(buffer.length);
  82487. tempVertexData.positions.set(buffer);
  82488. }
  82489. verticesCounts.push(tempVertexData.positions.length);
  82490. }
  82491. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  82492. var channel = Number(semantic.split("_")[1]);
  82493. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  82494. var uvs = new Float32Array(buffer.length);
  82495. uvs.set(buffer);
  82496. normalizeUVs(uvs);
  82497. tempVertexData.set(uvs, uvKind);
  82498. }
  82499. else if (semantic === "JOINT") {
  82500. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  82501. tempVertexData.matricesIndices.set(buffer);
  82502. }
  82503. else if (semantic === "WEIGHT") {
  82504. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  82505. tempVertexData.matricesWeights.set(buffer);
  82506. }
  82507. else if (semantic === "COLOR") {
  82508. tempVertexData.colors = new Float32Array(buffer.length);
  82509. tempVertexData.colors.set(buffer);
  82510. }
  82511. }
  82512. // Indices
  82513. accessor = gltfRuntime.accessors[primitive.indices];
  82514. if (accessor) {
  82515. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82516. tempVertexData.indices = new Int32Array(buffer.length);
  82517. tempVertexData.indices.set(buffer);
  82518. indexCounts.push(tempVertexData.indices.length);
  82519. }
  82520. else {
  82521. // Set indices on the fly
  82522. var indices = [];
  82523. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  82524. indices.push(j);
  82525. }
  82526. tempVertexData.indices = new Int32Array(indices);
  82527. indexCounts.push(tempVertexData.indices.length);
  82528. }
  82529. vertexData.merge(tempVertexData);
  82530. // Sub material
  82531. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  82532. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  82533. // Update vertices start and index start
  82534. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  82535. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  82536. }
  82537. }
  82538. var material;
  82539. if (subMaterials.length > 1) {
  82540. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  82541. material.subMaterials = subMaterials;
  82542. }
  82543. else {
  82544. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  82545. }
  82546. if (subMaterials.length === 1) {
  82547. material = subMaterials[0];
  82548. }
  82549. if (!newMesh.material) {
  82550. newMesh.material = material;
  82551. }
  82552. // Apply geometry
  82553. geometry.setAllVerticesData(vertexData, false);
  82554. newMesh.computeWorldMatrix(true);
  82555. // Apply submeshes
  82556. newMesh.subMeshes = [];
  82557. var index = 0;
  82558. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82559. var meshID = meshes[meshIndex];
  82560. var mesh = gltfRuntime.meshes[meshID];
  82561. if (!mesh) {
  82562. continue;
  82563. }
  82564. for (var i = 0; i < mesh.primitives.length; i++) {
  82565. if (mesh.primitives[i].mode !== 4) {
  82566. //continue;
  82567. }
  82568. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  82569. index++;
  82570. }
  82571. }
  82572. // Finish
  82573. return newMesh;
  82574. };
  82575. /**
  82576. * Configure node transformation from position, rotation and scaling
  82577. */
  82578. var configureNode = function (newNode, position, rotation, scaling) {
  82579. if (newNode.position) {
  82580. newNode.position = position;
  82581. }
  82582. if (newNode.rotationQuaternion || newNode.rotation) {
  82583. newNode.rotationQuaternion = rotation;
  82584. }
  82585. if (newNode.scaling) {
  82586. newNode.scaling = scaling;
  82587. }
  82588. };
  82589. /**
  82590. * Configures node from transformation matrix
  82591. */
  82592. var configureNodeFromMatrix = function (newNode, node, parent) {
  82593. if (node.matrix) {
  82594. var position = new BABYLON.Vector3(0, 0, 0);
  82595. var rotation = new BABYLON.Quaternion();
  82596. var scaling = new BABYLON.Vector3(0, 0, 0);
  82597. var mat = BABYLON.Matrix.FromArray(node.matrix);
  82598. mat.decompose(scaling, rotation, position);
  82599. configureNode(newNode, position, rotation, scaling);
  82600. }
  82601. else if (node.translation && node.rotation && node.scale) {
  82602. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  82603. }
  82604. newNode.computeWorldMatrix(true);
  82605. };
  82606. /**
  82607. * Imports a node
  82608. */
  82609. var importNode = function (gltfRuntime, node, id, parent) {
  82610. var lastNode = null;
  82611. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  82612. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  82613. return null;
  82614. }
  82615. }
  82616. // Meshes
  82617. if (node.skin) {
  82618. if (node.meshes) {
  82619. var skin = gltfRuntime.skins[node.skin];
  82620. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  82621. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  82622. if (newMesh.skeleton === null) {
  82623. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  82624. if (!skin.babylonSkeleton) {
  82625. skin.babylonSkeleton = newMesh.skeleton;
  82626. }
  82627. }
  82628. lastNode = newMesh;
  82629. }
  82630. }
  82631. else if (node.meshes) {
  82632. /**
  82633. * Improve meshes property
  82634. */
  82635. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  82636. lastNode = newMesh;
  82637. }
  82638. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  82639. var light = gltfRuntime.lights[node.light];
  82640. if (light) {
  82641. if (light.type === "ambient") {
  82642. var ambienLight = light[light.type];
  82643. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82644. hemiLight.name = node.name || "";
  82645. if (ambienLight.color) {
  82646. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  82647. }
  82648. lastNode = hemiLight;
  82649. }
  82650. else if (light.type === "directional") {
  82651. var directionalLight = light[light.type];
  82652. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82653. dirLight.name = node.name || "";
  82654. if (directionalLight.color) {
  82655. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  82656. }
  82657. lastNode = dirLight;
  82658. }
  82659. else if (light.type === "point") {
  82660. var pointLight = light[light.type];
  82661. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82662. ptLight.name = node.name || "";
  82663. if (pointLight.color) {
  82664. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  82665. }
  82666. lastNode = ptLight;
  82667. }
  82668. else if (light.type === "spot") {
  82669. var spotLight = light[light.type];
  82670. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  82671. spLight.name = node.name || "";
  82672. if (spotLight.color) {
  82673. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  82674. }
  82675. if (spotLight.fallOfAngle) {
  82676. spLight.angle = spotLight.fallOfAngle;
  82677. }
  82678. if (spotLight.fallOffExponent) {
  82679. spLight.exponent = spotLight.fallOffExponent;
  82680. }
  82681. lastNode = spLight;
  82682. }
  82683. }
  82684. }
  82685. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  82686. var camera = gltfRuntime.cameras[node.camera];
  82687. if (camera) {
  82688. if (camera.type === "orthographic") {
  82689. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82690. orthoCamera.name = node.name || "";
  82691. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  82692. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  82693. lastNode = orthoCamera;
  82694. }
  82695. else if (camera.type === "perspective") {
  82696. var perspectiveCamera = camera[camera.type];
  82697. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82698. persCamera.name = node.name || "";
  82699. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  82700. if (!perspectiveCamera.aspectRatio) {
  82701. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  82702. }
  82703. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  82704. persCamera.maxZ = perspectiveCamera.zfar;
  82705. persCamera.minZ = perspectiveCamera.znear;
  82706. }
  82707. lastNode = persCamera;
  82708. }
  82709. }
  82710. }
  82711. // Empty node
  82712. if (!node.jointName) {
  82713. if (node.babylonNode) {
  82714. return node.babylonNode;
  82715. }
  82716. else if (lastNode === null) {
  82717. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82718. node.babylonNode = dummy;
  82719. lastNode = dummy;
  82720. }
  82721. }
  82722. if (lastNode !== null) {
  82723. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  82724. configureNodeFromMatrix(lastNode, node, parent);
  82725. }
  82726. else {
  82727. var translation = node.translation || [0, 0, 0];
  82728. var rotation = node.rotation || [0, 0, 0, 1];
  82729. var scale = node.scale || [1, 1, 1];
  82730. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  82731. }
  82732. lastNode.updateCache(true);
  82733. node.babylonNode = lastNode;
  82734. }
  82735. return lastNode;
  82736. };
  82737. /**
  82738. * Traverses nodes and creates them
  82739. */
  82740. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  82741. if (meshIncluded === void 0) { meshIncluded = false; }
  82742. var node = gltfRuntime.nodes[id];
  82743. var newNode = null;
  82744. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  82745. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  82746. meshIncluded = true;
  82747. }
  82748. else {
  82749. meshIncluded = false;
  82750. }
  82751. }
  82752. else {
  82753. meshIncluded = true;
  82754. }
  82755. if (!node.jointName && meshIncluded) {
  82756. newNode = importNode(gltfRuntime, node, id, parent);
  82757. if (newNode !== null) {
  82758. newNode.id = id;
  82759. newNode.parent = parent;
  82760. }
  82761. }
  82762. if (node.children) {
  82763. for (var i = 0; i < node.children.length; i++) {
  82764. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  82765. }
  82766. }
  82767. };
  82768. /**
  82769. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  82770. */
  82771. var postLoad = function (gltfRuntime) {
  82772. // Nodes
  82773. var currentScene = gltfRuntime.currentScene;
  82774. if (currentScene) {
  82775. for (var i = 0; i < currentScene.nodes.length; i++) {
  82776. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  82777. }
  82778. }
  82779. else {
  82780. for (var thing in gltfRuntime.scenes) {
  82781. currentScene = gltfRuntime.scenes[thing];
  82782. for (var i = 0; i < currentScene.nodes.length; i++) {
  82783. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  82784. }
  82785. }
  82786. }
  82787. // Set animations
  82788. loadAnimations(gltfRuntime);
  82789. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  82790. var skeleton = gltfRuntime.scene.skeletons[i];
  82791. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  82792. }
  82793. };
  82794. /**
  82795. * onBind shaderrs callback to set uniforms and matrices
  82796. */
  82797. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  82798. var materialValues = material.values || technique.parameters;
  82799. for (var unif in unTreatedUniforms) {
  82800. var uniform = unTreatedUniforms[unif];
  82801. var type = uniform.type;
  82802. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  82803. if (uniform.semantic && !uniform.source && !uniform.node) {
  82804. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  82805. }
  82806. else if (uniform.semantic && (uniform.source || uniform.node)) {
  82807. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  82808. if (source === null) {
  82809. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  82810. }
  82811. if (source === null) {
  82812. continue;
  82813. }
  82814. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  82815. }
  82816. }
  82817. else {
  82818. var value = materialValues[technique.uniforms[unif]];
  82819. if (!value) {
  82820. continue;
  82821. }
  82822. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  82823. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  82824. if (texture === null || texture === undefined) {
  82825. continue;
  82826. }
  82827. shaderMaterial.getEffect().setTexture(unif, texture);
  82828. }
  82829. else {
  82830. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  82831. }
  82832. }
  82833. }
  82834. onSuccess(shaderMaterial);
  82835. };
  82836. /**
  82837. * Prepare uniforms to send the only one time
  82838. * Loads the appropriate textures
  82839. */
  82840. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  82841. var materialValues = material.values || technique.parameters;
  82842. var techniqueUniforms = technique.uniforms;
  82843. /**
  82844. * Prepare values here (not matrices)
  82845. */
  82846. for (var unif in unTreatedUniforms) {
  82847. var uniform = unTreatedUniforms[unif];
  82848. var type = uniform.type;
  82849. var value = materialValues[techniqueUniforms[unif]];
  82850. if (value === undefined) {
  82851. // In case the value is the same for all materials
  82852. value = uniform.value;
  82853. }
  82854. if (!value) {
  82855. continue;
  82856. }
  82857. var onLoadTexture = function (uniformName) {
  82858. return function (texture) {
  82859. if (uniform.value && uniformName) {
  82860. // Static uniform
  82861. shaderMaterial.setTexture(uniformName, texture);
  82862. delete unTreatedUniforms[uniformName];
  82863. }
  82864. };
  82865. };
  82866. // Texture (sampler2D)
  82867. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  82868. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  82869. }
  82870. else {
  82871. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  82872. // Static uniform
  82873. delete unTreatedUniforms[unif];
  82874. }
  82875. }
  82876. }
  82877. };
  82878. /**
  82879. * Shader compilation failed
  82880. */
  82881. var onShaderCompileError = function (program, shaderMaterial, onError) {
  82882. return function (effect, error) {
  82883. shaderMaterial.dispose(true);
  82884. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  82885. };
  82886. };
  82887. /**
  82888. * Shader compilation success
  82889. */
  82890. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  82891. return function (_) {
  82892. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  82893. shaderMaterial.onBind = function (mesh) {
  82894. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  82895. };
  82896. };
  82897. };
  82898. /**
  82899. * Returns the appropriate uniform if already handled by babylon
  82900. */
  82901. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  82902. for (var unif in technique.uniforms) {
  82903. var uniform = technique.uniforms[unif];
  82904. var uniformParameter = technique.parameters[uniform];
  82905. if (tokenizer.currentIdentifier === unif) {
  82906. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  82907. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  82908. if (transformIndex !== -1) {
  82909. delete unTreatedUniforms[unif];
  82910. return babylonTransforms[transformIndex];
  82911. }
  82912. }
  82913. }
  82914. }
  82915. return tokenizer.currentIdentifier;
  82916. };
  82917. /**
  82918. * All shaders loaded. Create materials one by one
  82919. */
  82920. var importMaterials = function (gltfRuntime) {
  82921. // Create materials
  82922. for (var mat in gltfRuntime.materials) {
  82923. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  82924. }
  82925. };
  82926. /**
  82927. * Implementation of the base glTF spec
  82928. */
  82929. var GLTFLoaderBase = /** @class */ (function () {
  82930. function GLTFLoaderBase() {
  82931. }
  82932. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  82933. var gltfRuntime = {
  82934. extensions: {},
  82935. accessors: {},
  82936. buffers: {},
  82937. bufferViews: {},
  82938. meshes: {},
  82939. lights: {},
  82940. cameras: {},
  82941. nodes: {},
  82942. images: {},
  82943. textures: {},
  82944. shaders: {},
  82945. programs: {},
  82946. samplers: {},
  82947. techniques: {},
  82948. materials: {},
  82949. animations: {},
  82950. skins: {},
  82951. extensionsUsed: [],
  82952. scenes: {},
  82953. buffersCount: 0,
  82954. shaderscount: 0,
  82955. scene: scene,
  82956. rootUrl: rootUrl,
  82957. loadedBufferCount: 0,
  82958. loadedBufferViews: {},
  82959. loadedShaderCount: 0,
  82960. importOnlyMeshes: false,
  82961. dummyNodes: []
  82962. };
  82963. // Parse
  82964. if (parsedData.extensions) {
  82965. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  82966. }
  82967. if (parsedData.extensionsUsed) {
  82968. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  82969. }
  82970. if (parsedData.buffers) {
  82971. parseBuffers(parsedData.buffers, gltfRuntime);
  82972. }
  82973. if (parsedData.bufferViews) {
  82974. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  82975. }
  82976. if (parsedData.accessors) {
  82977. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  82978. }
  82979. if (parsedData.meshes) {
  82980. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  82981. }
  82982. if (parsedData.lights) {
  82983. parseObject(parsedData.lights, "lights", gltfRuntime);
  82984. }
  82985. if (parsedData.cameras) {
  82986. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  82987. }
  82988. if (parsedData.nodes) {
  82989. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  82990. }
  82991. if (parsedData.images) {
  82992. parseObject(parsedData.images, "images", gltfRuntime);
  82993. }
  82994. if (parsedData.textures) {
  82995. parseObject(parsedData.textures, "textures", gltfRuntime);
  82996. }
  82997. if (parsedData.shaders) {
  82998. parseShaders(parsedData.shaders, gltfRuntime);
  82999. }
  83000. if (parsedData.programs) {
  83001. parseObject(parsedData.programs, "programs", gltfRuntime);
  83002. }
  83003. if (parsedData.samplers) {
  83004. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83005. }
  83006. if (parsedData.techniques) {
  83007. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83008. }
  83009. if (parsedData.materials) {
  83010. parseObject(parsedData.materials, "materials", gltfRuntime);
  83011. }
  83012. if (parsedData.animations) {
  83013. parseObject(parsedData.animations, "animations", gltfRuntime);
  83014. }
  83015. if (parsedData.skins) {
  83016. parseObject(parsedData.skins, "skins", gltfRuntime);
  83017. }
  83018. if (parsedData.scenes) {
  83019. gltfRuntime.scenes = parsedData.scenes;
  83020. }
  83021. if (parsedData.scene && parsedData.scenes) {
  83022. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83023. }
  83024. return gltfRuntime;
  83025. };
  83026. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83027. var buffer = gltfRuntime.buffers[id];
  83028. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83029. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83030. }
  83031. else {
  83032. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83033. if (request) {
  83034. onError(request.status + " " + request.statusText);
  83035. }
  83036. });
  83037. }
  83038. };
  83039. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83040. var texture = gltfRuntime.textures[id];
  83041. if (!texture || !texture.source) {
  83042. onError("");
  83043. return;
  83044. }
  83045. if (texture.babylonTexture) {
  83046. onSuccess(null);
  83047. return;
  83048. }
  83049. var source = gltfRuntime.images[texture.source];
  83050. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83051. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83052. }
  83053. else {
  83054. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83055. if (request) {
  83056. onError(request.status + " " + request.statusText);
  83057. }
  83058. });
  83059. }
  83060. };
  83061. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83062. var texture = gltfRuntime.textures[id];
  83063. if (texture.babylonTexture) {
  83064. onSuccess(texture.babylonTexture);
  83065. return;
  83066. }
  83067. var sampler = gltfRuntime.samplers[texture.sampler];
  83068. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83069. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83070. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83071. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83072. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83073. var blob = new Blob([buffer]);
  83074. var blobURL = URL.createObjectURL(blob);
  83075. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83076. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83077. if (sampler.wrapS !== undefined) {
  83078. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83079. }
  83080. if (sampler.wrapT !== undefined) {
  83081. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83082. }
  83083. newTexture.name = id;
  83084. texture.babylonTexture = newTexture;
  83085. onSuccess(newTexture);
  83086. };
  83087. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83088. var shader = gltfRuntime.shaders[id];
  83089. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83090. var shaderString = atob(shader.uri.split(",")[1]);
  83091. onSuccess(shaderString);
  83092. }
  83093. else {
  83094. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83095. if (request) {
  83096. onError(request.status + " " + request.statusText);
  83097. }
  83098. });
  83099. }
  83100. };
  83101. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83102. var material = gltfRuntime.materials[id];
  83103. if (!material.technique) {
  83104. if (onError) {
  83105. onError("No technique found.");
  83106. }
  83107. return;
  83108. }
  83109. var technique = gltfRuntime.techniques[material.technique];
  83110. if (!technique) {
  83111. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83112. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83113. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83114. onSuccess(defaultMaterial);
  83115. return;
  83116. }
  83117. var program = gltfRuntime.programs[technique.program];
  83118. var states = technique.states;
  83119. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83120. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83121. var newVertexShader = "";
  83122. var newPixelShader = "";
  83123. var vertexTokenizer = new Tokenizer(vertexShader);
  83124. var pixelTokenizer = new Tokenizer(pixelShader);
  83125. var unTreatedUniforms = {};
  83126. var uniforms = [];
  83127. var attributes = [];
  83128. var samplers = [];
  83129. // Fill uniform, sampler2D and attributes
  83130. for (var unif in technique.uniforms) {
  83131. var uniform = technique.uniforms[unif];
  83132. var uniformParameter = technique.parameters[uniform];
  83133. unTreatedUniforms[unif] = uniformParameter;
  83134. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83135. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83136. if (transformIndex !== -1) {
  83137. uniforms.push(babylonTransforms[transformIndex]);
  83138. delete unTreatedUniforms[unif];
  83139. }
  83140. else {
  83141. uniforms.push(unif);
  83142. }
  83143. }
  83144. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83145. samplers.push(unif);
  83146. }
  83147. else {
  83148. uniforms.push(unif);
  83149. }
  83150. }
  83151. for (var attr in technique.attributes) {
  83152. var attribute = technique.attributes[attr];
  83153. var attributeParameter = technique.parameters[attribute];
  83154. if (attributeParameter.semantic) {
  83155. attributes.push(getAttribute(attributeParameter));
  83156. }
  83157. }
  83158. // Configure vertex shader
  83159. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83160. var tokenType = vertexTokenizer.currentToken;
  83161. if (tokenType !== ETokenType.IDENTIFIER) {
  83162. newVertexShader += vertexTokenizer.currentString;
  83163. continue;
  83164. }
  83165. var foundAttribute = false;
  83166. for (var attr in technique.attributes) {
  83167. var attribute = technique.attributes[attr];
  83168. var attributeParameter = technique.parameters[attribute];
  83169. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83170. newVertexShader += getAttribute(attributeParameter);
  83171. foundAttribute = true;
  83172. break;
  83173. }
  83174. }
  83175. if (foundAttribute) {
  83176. continue;
  83177. }
  83178. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83179. }
  83180. // Configure pixel shader
  83181. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83182. var tokenType = pixelTokenizer.currentToken;
  83183. if (tokenType !== ETokenType.IDENTIFIER) {
  83184. newPixelShader += pixelTokenizer.currentString;
  83185. continue;
  83186. }
  83187. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83188. }
  83189. // Create shader material
  83190. var shaderPath = {
  83191. vertex: program.vertexShader + id,
  83192. fragment: program.fragmentShader + id
  83193. };
  83194. var options = {
  83195. attributes: attributes,
  83196. uniforms: uniforms,
  83197. samplers: samplers,
  83198. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83199. };
  83200. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83201. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83202. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83203. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83204. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83205. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83206. if (states && states.functions) {
  83207. var functions = states.functions;
  83208. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83209. shaderMaterial.backFaceCulling = false;
  83210. }
  83211. var blendFunc = functions.blendFuncSeparate;
  83212. if (blendFunc) {
  83213. 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) {
  83214. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83215. }
  83216. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83217. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83218. }
  83219. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83220. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83221. }
  83222. 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) {
  83223. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83224. }
  83225. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83226. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83227. }
  83228. 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) {
  83229. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83230. }
  83231. }
  83232. }
  83233. };
  83234. return GLTFLoaderBase;
  83235. }());
  83236. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83237. /**
  83238. * glTF V1 Loader
  83239. */
  83240. var GLTFLoader = /** @class */ (function () {
  83241. function GLTFLoader() {
  83242. // #region Stubs for IGLTFLoader interface
  83243. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83244. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83245. this.compileMaterials = false;
  83246. this.useClipPlane = false;
  83247. this.compileShadowGenerators = false;
  83248. this.onDisposeObservable = new BABYLON.Observable();
  83249. this.onMeshLoadedObservable = new BABYLON.Observable();
  83250. this.onTextureLoadedObservable = new BABYLON.Observable();
  83251. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83252. this.onCompleteObservable = new BABYLON.Observable();
  83253. }
  83254. GLTFLoader.RegisterExtension = function (extension) {
  83255. if (GLTFLoader.Extensions[extension.name]) {
  83256. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83257. return;
  83258. }
  83259. GLTFLoader.Extensions[extension.name] = extension;
  83260. };
  83261. GLTFLoader.prototype.dispose = function () { };
  83262. // #endregion
  83263. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83264. var _this = this;
  83265. scene.useRightHandedSystem = true;
  83266. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83267. gltfRuntime.importOnlyMeshes = true;
  83268. if (meshesNames === "") {
  83269. gltfRuntime.importMeshesNames = [];
  83270. }
  83271. else if (typeof meshesNames === "string") {
  83272. gltfRuntime.importMeshesNames = [meshesNames];
  83273. }
  83274. else if (meshesNames && !(meshesNames instanceof Array)) {
  83275. gltfRuntime.importMeshesNames = [meshesNames];
  83276. }
  83277. else {
  83278. gltfRuntime.importMeshesNames = [];
  83279. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83280. }
  83281. // Create nodes
  83282. _this._createNodes(gltfRuntime);
  83283. var meshes = new Array();
  83284. var skeletons = new Array();
  83285. // Fill arrays of meshes and skeletons
  83286. for (var nde in gltfRuntime.nodes) {
  83287. var node = gltfRuntime.nodes[nde];
  83288. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83289. meshes.push(node.babylonNode);
  83290. }
  83291. }
  83292. for (var skl in gltfRuntime.skins) {
  83293. var skin = gltfRuntime.skins[skl];
  83294. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83295. skeletons.push(skin.babylonSkeleton);
  83296. }
  83297. }
  83298. // Load buffers, shaders, materials, etc.
  83299. _this._loadBuffersAsync(gltfRuntime, function () {
  83300. _this._loadShadersAsync(gltfRuntime, function () {
  83301. importMaterials(gltfRuntime);
  83302. postLoad(gltfRuntime);
  83303. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83304. onSuccess(meshes, [], skeletons);
  83305. }
  83306. });
  83307. }, onProgress);
  83308. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83309. onSuccess(meshes, [], skeletons);
  83310. }
  83311. }, onError);
  83312. return true;
  83313. };
  83314. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83315. var _this = this;
  83316. scene.useRightHandedSystem = true;
  83317. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83318. // Load runtime extensios
  83319. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83320. // Create nodes
  83321. _this._createNodes(gltfRuntime);
  83322. // Load buffers, shaders, materials, etc.
  83323. _this._loadBuffersAsync(gltfRuntime, function () {
  83324. _this._loadShadersAsync(gltfRuntime, function () {
  83325. importMaterials(gltfRuntime);
  83326. postLoad(gltfRuntime);
  83327. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83328. onSuccess();
  83329. }
  83330. });
  83331. });
  83332. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83333. onSuccess();
  83334. }
  83335. }, onError);
  83336. }, onError);
  83337. };
  83338. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83339. var hasShaders = false;
  83340. var processShader = function (sha, shader) {
  83341. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83342. gltfRuntime.loadedShaderCount++;
  83343. if (shaderString) {
  83344. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83345. }
  83346. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83347. onload();
  83348. }
  83349. }, function () {
  83350. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83351. });
  83352. };
  83353. for (var sha in gltfRuntime.shaders) {
  83354. hasShaders = true;
  83355. var shader = gltfRuntime.shaders[sha];
  83356. if (shader) {
  83357. processShader.bind(this, sha, shader)();
  83358. }
  83359. else {
  83360. BABYLON.Tools.Error("No shader named: " + sha);
  83361. }
  83362. }
  83363. if (!hasShaders) {
  83364. onload();
  83365. }
  83366. };
  83367. ;
  83368. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83369. var hasBuffers = false;
  83370. var processBuffer = function (buf, buffer) {
  83371. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83372. gltfRuntime.loadedBufferCount++;
  83373. if (bufferView) {
  83374. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83375. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83376. }
  83377. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83378. }
  83379. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83380. onLoad();
  83381. }
  83382. }, function () {
  83383. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83384. });
  83385. };
  83386. for (var buf in gltfRuntime.buffers) {
  83387. hasBuffers = true;
  83388. var buffer = gltfRuntime.buffers[buf];
  83389. if (buffer) {
  83390. processBuffer.bind(this, buf, buffer)();
  83391. }
  83392. else {
  83393. BABYLON.Tools.Error("No buffer named: " + buf);
  83394. }
  83395. }
  83396. if (!hasBuffers) {
  83397. onLoad();
  83398. }
  83399. };
  83400. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83401. var currentScene = gltfRuntime.currentScene;
  83402. if (currentScene) {
  83403. // Only one scene even if multiple scenes are defined
  83404. for (var i = 0; i < currentScene.nodes.length; i++) {
  83405. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83406. }
  83407. }
  83408. else {
  83409. // Load all scenes
  83410. for (var thing in gltfRuntime.scenes) {
  83411. currentScene = gltfRuntime.scenes[thing];
  83412. for (var i = 0; i < currentScene.nodes.length; i++) {
  83413. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83414. }
  83415. }
  83416. }
  83417. };
  83418. GLTFLoader.Extensions = {};
  83419. return GLTFLoader;
  83420. }());
  83421. GLTF1.GLTFLoader = GLTFLoader;
  83422. ;
  83423. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83424. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83425. })(BABYLON || (BABYLON = {}));
  83426. //# sourceMappingURL=babylon.glTFLoader.js.map
  83427. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83428. var BABYLON;
  83429. (function (BABYLON) {
  83430. var GLTF1;
  83431. (function (GLTF1) {
  83432. /**
  83433. * Utils functions for GLTF
  83434. */
  83435. var GLTFUtils = /** @class */ (function () {
  83436. function GLTFUtils() {
  83437. }
  83438. /**
  83439. * Sets the given "parameter" matrix
  83440. * @param scene: the {BABYLON.Scene} object
  83441. * @param source: the source node where to pick the matrix
  83442. * @param parameter: the GLTF technique parameter
  83443. * @param uniformName: the name of the shader's uniform
  83444. * @param shaderMaterial: the shader material
  83445. */
  83446. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83447. var mat = null;
  83448. if (parameter.semantic === "MODEL") {
  83449. mat = source.getWorldMatrix();
  83450. }
  83451. else if (parameter.semantic === "PROJECTION") {
  83452. mat = scene.getProjectionMatrix();
  83453. }
  83454. else if (parameter.semantic === "VIEW") {
  83455. mat = scene.getViewMatrix();
  83456. }
  83457. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83458. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83459. }
  83460. else if (parameter.semantic === "MODELVIEW") {
  83461. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83462. }
  83463. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  83464. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  83465. }
  83466. else if (parameter.semantic === "MODELINVERSE") {
  83467. mat = source.getWorldMatrix().invert();
  83468. }
  83469. else if (parameter.semantic === "VIEWINVERSE") {
  83470. mat = scene.getViewMatrix().invert();
  83471. }
  83472. else if (parameter.semantic === "PROJECTIONINVERSE") {
  83473. mat = scene.getProjectionMatrix().invert();
  83474. }
  83475. else if (parameter.semantic === "MODELVIEWINVERSE") {
  83476. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  83477. }
  83478. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  83479. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  83480. }
  83481. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  83482. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  83483. }
  83484. else {
  83485. debugger;
  83486. }
  83487. if (mat) {
  83488. switch (parameter.type) {
  83489. case GLTF1.EParameterType.FLOAT_MAT2:
  83490. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  83491. break;
  83492. case GLTF1.EParameterType.FLOAT_MAT3:
  83493. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  83494. break;
  83495. case GLTF1.EParameterType.FLOAT_MAT4:
  83496. shaderMaterial.setMatrix(uniformName, mat);
  83497. break;
  83498. default: break;
  83499. }
  83500. }
  83501. };
  83502. /**
  83503. * Sets the given "parameter" matrix
  83504. * @param shaderMaterial: the shader material
  83505. * @param uniform: the name of the shader's uniform
  83506. * @param value: the value of the uniform
  83507. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  83508. */
  83509. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  83510. switch (type) {
  83511. case GLTF1.EParameterType.FLOAT:
  83512. shaderMaterial.setFloat(uniform, value);
  83513. return true;
  83514. case GLTF1.EParameterType.FLOAT_VEC2:
  83515. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  83516. return true;
  83517. case GLTF1.EParameterType.FLOAT_VEC3:
  83518. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  83519. return true;
  83520. case GLTF1.EParameterType.FLOAT_VEC4:
  83521. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  83522. return true;
  83523. default: return false;
  83524. }
  83525. };
  83526. /**
  83527. * If the uri is a base64 string
  83528. * @param uri: the uri to test
  83529. */
  83530. GLTFUtils.IsBase64 = function (uri) {
  83531. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83532. };
  83533. /**
  83534. * Decode the base64 uri
  83535. * @param uri: the uri to decode
  83536. */
  83537. GLTFUtils.DecodeBase64 = function (uri) {
  83538. var decodedString = atob(uri.split(",")[1]);
  83539. var bufferLength = decodedString.length;
  83540. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83541. for (var i = 0; i < bufferLength; i++) {
  83542. bufferView[i] = decodedString.charCodeAt(i);
  83543. }
  83544. return bufferView.buffer;
  83545. };
  83546. /**
  83547. * Returns the wrap mode of the texture
  83548. * @param mode: the mode value
  83549. */
  83550. GLTFUtils.GetWrapMode = function (mode) {
  83551. switch (mode) {
  83552. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83553. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83554. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83555. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83556. }
  83557. };
  83558. /**
  83559. * Returns the byte stride giving an accessor
  83560. * @param accessor: the GLTF accessor objet
  83561. */
  83562. GLTFUtils.GetByteStrideFromType = function (accessor) {
  83563. // Needs this function since "byteStride" isn't requiered in glTF format
  83564. var type = accessor.type;
  83565. switch (type) {
  83566. case "VEC2": return 2;
  83567. case "VEC3": return 3;
  83568. case "VEC4": return 4;
  83569. case "MAT2": return 4;
  83570. case "MAT3": return 9;
  83571. case "MAT4": return 16;
  83572. default: return 1;
  83573. }
  83574. };
  83575. /**
  83576. * Returns the texture filter mode giving a mode value
  83577. * @param mode: the filter mode value
  83578. */
  83579. GLTFUtils.GetTextureFilterMode = function (mode) {
  83580. switch (mode) {
  83581. case GLTF1.ETextureFilterType.LINEAR:
  83582. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  83583. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  83584. case GLTF1.ETextureFilterType.NEAREST:
  83585. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  83586. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83587. }
  83588. };
  83589. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  83590. var byteOffset = bufferView.byteOffset + byteOffset;
  83591. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  83592. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  83593. throw new Error("Buffer access is out of range");
  83594. }
  83595. var buffer = loadedBufferView.buffer;
  83596. byteOffset += loadedBufferView.byteOffset;
  83597. switch (componentType) {
  83598. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  83599. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  83600. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  83601. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  83602. default: return new Float32Array(buffer, byteOffset, byteLength);
  83603. }
  83604. };
  83605. /**
  83606. * Returns a buffer from its accessor
  83607. * @param gltfRuntime: the GLTF runtime
  83608. * @param accessor: the GLTF accessor
  83609. */
  83610. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  83611. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  83612. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  83613. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  83614. };
  83615. /**
  83616. * Decodes a buffer view into a string
  83617. * @param view: the buffer view
  83618. */
  83619. GLTFUtils.DecodeBufferToText = function (view) {
  83620. var result = "";
  83621. var length = view.byteLength;
  83622. for (var i = 0; i < length; ++i) {
  83623. result += String.fromCharCode(view[i]);
  83624. }
  83625. return result;
  83626. };
  83627. /**
  83628. * Returns the default material of gltf. Related to
  83629. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  83630. * @param scene: the Babylon.js scene
  83631. */
  83632. GLTFUtils.GetDefaultMaterial = function (scene) {
  83633. if (!GLTFUtils._DefaultMaterial) {
  83634. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  83635. "precision highp float;",
  83636. "",
  83637. "uniform mat4 worldView;",
  83638. "uniform mat4 projection;",
  83639. "",
  83640. "attribute vec3 position;",
  83641. "",
  83642. "void main(void)",
  83643. "{",
  83644. " gl_Position = projection * worldView * vec4(position, 1.0);",
  83645. "}"
  83646. ].join("\n");
  83647. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  83648. "precision highp float;",
  83649. "",
  83650. "uniform vec4 u_emission;",
  83651. "",
  83652. "void main(void)",
  83653. "{",
  83654. " gl_FragColor = u_emission;",
  83655. "}"
  83656. ].join("\n");
  83657. var shaderPath = {
  83658. vertex: "GLTFDefaultMaterial",
  83659. fragment: "GLTFDefaultMaterial"
  83660. };
  83661. var options = {
  83662. attributes: ["position"],
  83663. uniforms: ["worldView", "projection", "u_emission"],
  83664. samplers: new Array(),
  83665. needAlphaBlending: false
  83666. };
  83667. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  83668. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  83669. }
  83670. return GLTFUtils._DefaultMaterial;
  83671. };
  83672. // The GLTF default material
  83673. GLTFUtils._DefaultMaterial = null;
  83674. return GLTFUtils;
  83675. }());
  83676. GLTF1.GLTFUtils = GLTFUtils;
  83677. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83678. })(BABYLON || (BABYLON = {}));
  83679. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  83680. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83681. var BABYLON;
  83682. (function (BABYLON) {
  83683. var GLTF1;
  83684. (function (GLTF1) {
  83685. var GLTFLoaderExtension = /** @class */ (function () {
  83686. function GLTFLoaderExtension(name) {
  83687. this._name = name;
  83688. }
  83689. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  83690. get: function () {
  83691. return this._name;
  83692. },
  83693. enumerable: true,
  83694. configurable: true
  83695. });
  83696. /**
  83697. * Defines an override for loading the runtime
  83698. * Return true to stop further extensions from loading the runtime
  83699. */
  83700. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  83701. return false;
  83702. };
  83703. /**
  83704. * Defines an onverride for creating gltf runtime
  83705. * Return true to stop further extensions from creating the runtime
  83706. */
  83707. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  83708. return false;
  83709. };
  83710. /**
  83711. * Defines an override for loading buffers
  83712. * Return true to stop further extensions from loading this buffer
  83713. */
  83714. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83715. return false;
  83716. };
  83717. /**
  83718. * Defines an override for loading texture buffers
  83719. * Return true to stop further extensions from loading this texture data
  83720. */
  83721. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83722. return false;
  83723. };
  83724. /**
  83725. * Defines an override for creating textures
  83726. * Return true to stop further extensions from loading this texture
  83727. */
  83728. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83729. return false;
  83730. };
  83731. /**
  83732. * Defines an override for loading shader strings
  83733. * Return true to stop further extensions from loading this shader data
  83734. */
  83735. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83736. return false;
  83737. };
  83738. /**
  83739. * Defines an override for loading materials
  83740. * Return true to stop further extensions from loading this material
  83741. */
  83742. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83743. return false;
  83744. };
  83745. // ---------
  83746. // Utilities
  83747. // ---------
  83748. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  83749. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83750. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  83751. }, function () {
  83752. setTimeout(function () {
  83753. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  83754. });
  83755. });
  83756. };
  83757. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  83758. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83759. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  83760. }, function () {
  83761. setTimeout(function () {
  83762. onSuccess();
  83763. });
  83764. });
  83765. };
  83766. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83767. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83768. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  83769. }, function () {
  83770. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  83771. });
  83772. };
  83773. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  83774. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  83775. };
  83776. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83777. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83778. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  83779. }, function () {
  83780. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  83781. });
  83782. };
  83783. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83784. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83785. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  83786. }, function () {
  83787. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  83788. });
  83789. };
  83790. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83791. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83792. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  83793. }, function () {
  83794. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  83795. });
  83796. };
  83797. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83798. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83799. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  83800. }, function () {
  83801. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  83802. });
  83803. };
  83804. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  83805. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  83806. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  83807. if (func(loaderExtension)) {
  83808. return;
  83809. }
  83810. }
  83811. defaultFunc();
  83812. };
  83813. return GLTFLoaderExtension;
  83814. }());
  83815. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  83816. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83817. })(BABYLON || (BABYLON = {}));
  83818. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  83819. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83820. var BABYLON;
  83821. (function (BABYLON) {
  83822. var GLTF1;
  83823. (function (GLTF1) {
  83824. var BinaryExtensionBufferName = "binary_glTF";
  83825. ;
  83826. ;
  83827. var GLTFBinaryExtension = /** @class */ (function (_super) {
  83828. __extends(GLTFBinaryExtension, _super);
  83829. function GLTFBinaryExtension() {
  83830. return _super.call(this, "KHR_binary_glTF") || this;
  83831. }
  83832. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  83833. var extensionsUsed = data.json.extensionsUsed;
  83834. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  83835. return false;
  83836. }
  83837. this._bin = data.bin;
  83838. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  83839. return true;
  83840. };
  83841. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83842. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  83843. return false;
  83844. }
  83845. if (id !== BinaryExtensionBufferName) {
  83846. return false;
  83847. }
  83848. onSuccess(this._bin);
  83849. return true;
  83850. };
  83851. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83852. var texture = gltfRuntime.textures[id];
  83853. var source = gltfRuntime.images[texture.source];
  83854. if (!source.extensions || !(this.name in source.extensions)) {
  83855. return false;
  83856. }
  83857. var sourceExt = source.extensions[this.name];
  83858. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  83859. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  83860. onSuccess(buffer);
  83861. return true;
  83862. };
  83863. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83864. var shader = gltfRuntime.shaders[id];
  83865. if (!shader.extensions || !(this.name in shader.extensions)) {
  83866. return false;
  83867. }
  83868. var binaryExtensionShader = shader.extensions[this.name];
  83869. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  83870. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  83871. setTimeout(function () {
  83872. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  83873. onSuccess(shaderString);
  83874. });
  83875. return true;
  83876. };
  83877. return GLTFBinaryExtension;
  83878. }(GLTF1.GLTFLoaderExtension));
  83879. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  83880. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  83881. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83882. })(BABYLON || (BABYLON = {}));
  83883. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  83884. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83885. var BABYLON;
  83886. (function (BABYLON) {
  83887. var GLTF1;
  83888. (function (GLTF1) {
  83889. ;
  83890. ;
  83891. ;
  83892. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  83893. __extends(GLTFMaterialsCommonExtension, _super);
  83894. function GLTFMaterialsCommonExtension() {
  83895. return _super.call(this, "KHR_materials_common") || this;
  83896. }
  83897. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  83898. if (!gltfRuntime.extensions)
  83899. return false;
  83900. var extension = gltfRuntime.extensions[this.name];
  83901. if (!extension)
  83902. return false;
  83903. // Create lights
  83904. var lights = extension.lights;
  83905. if (lights) {
  83906. for (var thing in lights) {
  83907. var light = lights[thing];
  83908. switch (light.type) {
  83909. case "ambient":
  83910. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  83911. var ambient = light.ambient;
  83912. if (ambient) {
  83913. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  83914. }
  83915. break;
  83916. case "point":
  83917. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  83918. var point = light.point;
  83919. if (point) {
  83920. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  83921. }
  83922. break;
  83923. case "directional":
  83924. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  83925. var directional = light.directional;
  83926. if (directional) {
  83927. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  83928. }
  83929. break;
  83930. case "spot":
  83931. var spot = light.spot;
  83932. if (spot) {
  83933. 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);
  83934. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  83935. }
  83936. break;
  83937. default:
  83938. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  83939. break;
  83940. }
  83941. }
  83942. }
  83943. return false;
  83944. };
  83945. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83946. var material = gltfRuntime.materials[id];
  83947. if (!material || !material.extensions)
  83948. return false;
  83949. var extension = material.extensions[this.name];
  83950. if (!extension)
  83951. return false;
  83952. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83953. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83954. if (extension.technique === "CONSTANT") {
  83955. standardMaterial.disableLighting = true;
  83956. }
  83957. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  83958. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  83959. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  83960. // Ambient
  83961. if (typeof extension.values.ambient === "string") {
  83962. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  83963. }
  83964. else {
  83965. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  83966. }
  83967. // Diffuse
  83968. if (typeof extension.values.diffuse === "string") {
  83969. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  83970. }
  83971. else {
  83972. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  83973. }
  83974. // Emission
  83975. if (typeof extension.values.emission === "string") {
  83976. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  83977. }
  83978. else {
  83979. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  83980. }
  83981. // Specular
  83982. if (typeof extension.values.specular === "string") {
  83983. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  83984. }
  83985. else {
  83986. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  83987. }
  83988. return true;
  83989. };
  83990. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  83991. // Create buffer from texture url
  83992. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  83993. // Create texture from buffer
  83994. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  83995. }, onError);
  83996. };
  83997. return GLTFMaterialsCommonExtension;
  83998. }(GLTF1.GLTFLoaderExtension));
  83999. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84000. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84001. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84002. })(BABYLON || (BABYLON = {}));
  84003. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84004. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84005. var BABYLON;
  84006. (function (BABYLON) {
  84007. var GLTF2;
  84008. (function (GLTF2) {
  84009. /**
  84010. * Enums
  84011. */
  84012. var EComponentType;
  84013. (function (EComponentType) {
  84014. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84015. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84016. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84017. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84018. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84019. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84020. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84021. var EMeshPrimitiveMode;
  84022. (function (EMeshPrimitiveMode) {
  84023. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84024. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84025. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84026. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84027. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84028. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84029. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84030. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84031. var ETextureMagFilter;
  84032. (function (ETextureMagFilter) {
  84033. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84034. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84035. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84036. var ETextureMinFilter;
  84037. (function (ETextureMinFilter) {
  84038. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84039. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84040. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84041. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84042. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84043. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84044. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84045. var ETextureWrapMode;
  84046. (function (ETextureWrapMode) {
  84047. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84048. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84049. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84050. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84051. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84052. })(BABYLON || (BABYLON = {}));
  84053. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84054. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84055. var BABYLON;
  84056. (function (BABYLON) {
  84057. var GLTF2;
  84058. (function (GLTF2) {
  84059. var GLTFLoaderTracker = /** @class */ (function () {
  84060. function GLTFLoaderTracker(onComplete) {
  84061. this._pendingCount = 0;
  84062. this._callback = onComplete;
  84063. }
  84064. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84065. this._pendingCount++;
  84066. };
  84067. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84068. if (--this._pendingCount === 0) {
  84069. this._callback();
  84070. }
  84071. };
  84072. return GLTFLoaderTracker;
  84073. }());
  84074. var GLTFLoader = /** @class */ (function () {
  84075. function GLTFLoader() {
  84076. this._disposed = false;
  84077. this._defaultSampler = {};
  84078. this._renderReady = false;
  84079. this._requests = new Array();
  84080. this._renderReadyObservable = new BABYLON.Observable();
  84081. // Count of pending work that needs to complete before the asset is rendered.
  84082. this._renderPendingCount = 0;
  84083. // Count of pending work that needs to complete before the loader is disposed.
  84084. this._loaderPendingCount = 0;
  84085. this._loaderTrackers = new Array();
  84086. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84087. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84088. this.compileMaterials = false;
  84089. this.useClipPlane = false;
  84090. this.compileShadowGenerators = false;
  84091. this.onDisposeObservable = new BABYLON.Observable();
  84092. this.onMeshLoadedObservable = new BABYLON.Observable();
  84093. this.onTextureLoadedObservable = new BABYLON.Observable();
  84094. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84095. this.onCompleteObservable = new BABYLON.Observable();
  84096. }
  84097. GLTFLoader.RegisterExtension = function (extension) {
  84098. if (GLTFLoader.Extensions[extension.name]) {
  84099. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84100. return;
  84101. }
  84102. GLTFLoader.Extensions[extension.name] = extension;
  84103. // Keep the order of registration so that extensions registered first are called first.
  84104. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84105. };
  84106. GLTFLoader.prototype.dispose = function () {
  84107. if (this._disposed) {
  84108. return;
  84109. }
  84110. this._disposed = true;
  84111. this._abortRequests();
  84112. this._releaseResources();
  84113. this.onDisposeObservable.notifyObservers(this);
  84114. };
  84115. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84116. var _this = this;
  84117. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84118. if (onSuccess) {
  84119. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84120. }
  84121. }, onProgress, onError);
  84122. };
  84123. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84124. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84125. };
  84126. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84127. var _this = this;
  84128. this._babylonScene = scene;
  84129. this._rootUrl = rootUrl;
  84130. this._successCallback = onSuccess;
  84131. this._progressCallback = onProgress;
  84132. this._errorCallback = onError;
  84133. this._tryCatchOnError(function () {
  84134. _this._loadData(data);
  84135. _this._addPendingData(_this);
  84136. _this._loadDefaultScene(nodeNames);
  84137. _this._loadAnimations();
  84138. _this._removePendingData(_this);
  84139. });
  84140. };
  84141. GLTFLoader.prototype._onProgress = function () {
  84142. if (!this._progressCallback) {
  84143. return;
  84144. }
  84145. var lengthComputable = true;
  84146. var loaded = 0;
  84147. var total = 0;
  84148. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84149. var request = _a[_i];
  84150. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84151. return;
  84152. }
  84153. lengthComputable = lengthComputable && request._lengthComputable;
  84154. loaded += request._loaded;
  84155. total += request._total;
  84156. }
  84157. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84158. };
  84159. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84160. if (this._renderReady) {
  84161. func();
  84162. }
  84163. else {
  84164. this._renderReadyObservable.add(func);
  84165. }
  84166. };
  84167. GLTFLoader.prototype._onRenderReady = function () {
  84168. this._rootNode.babylonMesh.setEnabled(true);
  84169. this._startAnimations();
  84170. if (this._successCallback) {
  84171. this._successCallback();
  84172. }
  84173. this._renderReadyObservable.notifyObservers(this);
  84174. };
  84175. GLTFLoader.prototype._onComplete = function () {
  84176. this._abortRequests();
  84177. this._releaseResources();
  84178. this.onCompleteObservable.notifyObservers(this);
  84179. };
  84180. GLTFLoader.prototype._loadData = function (data) {
  84181. this._gltf = data.json;
  84182. // Assign the index of each object for convinience.
  84183. GLTFLoader._AssignIndices(this._gltf.accessors);
  84184. GLTFLoader._AssignIndices(this._gltf.animations);
  84185. GLTFLoader._AssignIndices(this._gltf.buffers);
  84186. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84187. GLTFLoader._AssignIndices(this._gltf.images);
  84188. GLTFLoader._AssignIndices(this._gltf.materials);
  84189. GLTFLoader._AssignIndices(this._gltf.meshes);
  84190. GLTFLoader._AssignIndices(this._gltf.nodes);
  84191. GLTFLoader._AssignIndices(this._gltf.samplers);
  84192. GLTFLoader._AssignIndices(this._gltf.scenes);
  84193. GLTFLoader._AssignIndices(this._gltf.skins);
  84194. GLTFLoader._AssignIndices(this._gltf.textures);
  84195. if (data.bin) {
  84196. var buffers = this._gltf.buffers;
  84197. if (buffers && buffers[0] && !buffers[0].uri) {
  84198. var binaryBuffer = buffers[0];
  84199. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84200. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84201. }
  84202. binaryBuffer.loadedData = data.bin;
  84203. }
  84204. else {
  84205. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84206. }
  84207. }
  84208. };
  84209. GLTFLoader.prototype._getMeshes = function () {
  84210. var meshes = new Array();
  84211. // Root mesh is always first.
  84212. meshes.push(this._rootNode.babylonMesh);
  84213. var nodes = this._gltf.nodes;
  84214. if (nodes) {
  84215. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84216. var node = nodes_1[_i];
  84217. if (node.babylonMesh) {
  84218. meshes.push(node.babylonMesh);
  84219. }
  84220. }
  84221. }
  84222. return meshes;
  84223. };
  84224. GLTFLoader.prototype._getSkeletons = function () {
  84225. var skeletons = new Array();
  84226. var skins = this._gltf.skins;
  84227. if (skins) {
  84228. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84229. var skin = skins_1[_i];
  84230. if (skin.babylonSkeleton) {
  84231. skeletons.push(skin.babylonSkeleton);
  84232. }
  84233. }
  84234. }
  84235. return skeletons;
  84236. };
  84237. GLTFLoader.prototype._startAnimations = function () {
  84238. var animations = this._gltf.animations;
  84239. if (!animations) {
  84240. return;
  84241. }
  84242. switch (this.animationStartMode) {
  84243. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84244. // do nothing
  84245. break;
  84246. }
  84247. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84248. var animation = animations[0];
  84249. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  84250. var target = _a[_i];
  84251. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84252. }
  84253. break;
  84254. }
  84255. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84256. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  84257. var animation = animations_1[_b];
  84258. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  84259. var target = _d[_c];
  84260. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84261. }
  84262. }
  84263. break;
  84264. }
  84265. default: {
  84266. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84267. return;
  84268. }
  84269. }
  84270. };
  84271. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84272. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84273. if (!scene) {
  84274. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84275. }
  84276. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84277. };
  84278. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84279. var _this = this;
  84280. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84281. switch (this.coordinateSystemMode) {
  84282. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84283. if (!this._babylonScene.useRightHandedSystem) {
  84284. this._rootNode.rotation = [0, 1, 0, 0];
  84285. this._rootNode.scale = [1, 1, -1];
  84286. this._loadTransform(this._rootNode);
  84287. }
  84288. break;
  84289. }
  84290. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84291. this._babylonScene.useRightHandedSystem = true;
  84292. break;
  84293. }
  84294. default: {
  84295. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84296. return;
  84297. }
  84298. }
  84299. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84300. var nodeIndices = scene.nodes;
  84301. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84302. node.parent = parentNode;
  84303. return true;
  84304. }, this._rootNode);
  84305. if (nodeNames) {
  84306. if (!(nodeNames instanceof Array)) {
  84307. nodeNames = [nodeNames];
  84308. }
  84309. var filteredNodeIndices_1 = new Array();
  84310. this._traverseNodes(context, nodeIndices, function (node) {
  84311. if (nodeNames.indexOf(node.name) !== -1) {
  84312. filteredNodeIndices_1.push(node.index);
  84313. node.parent = _this._rootNode;
  84314. return false;
  84315. }
  84316. return true;
  84317. }, this._rootNode);
  84318. nodeIndices = filteredNodeIndices_1;
  84319. }
  84320. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84321. var index = nodeIndices_1[_i];
  84322. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84323. if (!node) {
  84324. throw new Error(context + ": Failed to find node " + index);
  84325. }
  84326. this._loadNode("#/nodes/" + index, node);
  84327. }
  84328. // Disable the root mesh until the asset is ready to render.
  84329. this._rootNode.babylonMesh.setEnabled(false);
  84330. };
  84331. GLTFLoader.prototype._loadNode = function (context, node) {
  84332. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84333. return;
  84334. }
  84335. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84336. this._loadTransform(node);
  84337. if (node.mesh != null) {
  84338. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84339. if (!mesh) {
  84340. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84341. }
  84342. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84343. }
  84344. node.babylonMesh.parent = node.parent.babylonMesh;
  84345. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84346. node.babylonAnimationTargets.push(node.babylonMesh);
  84347. if (node.skin != null) {
  84348. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84349. if (!skin_1) {
  84350. throw new Error(context + ": Failed to find skin " + node.skin);
  84351. }
  84352. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84353. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84354. node.babylonMesh._refreshBoundingInfo(true);
  84355. });
  84356. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84357. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84358. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84359. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84360. }
  84361. if (node.camera != null) {
  84362. // TODO: handle cameras
  84363. }
  84364. if (node.children) {
  84365. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84366. var index = _a[_i];
  84367. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84368. if (!childNode) {
  84369. throw new Error(context + ": Failed to find child node " + index);
  84370. }
  84371. this._loadNode("#/nodes/" + index, childNode);
  84372. }
  84373. }
  84374. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84375. };
  84376. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84377. var _this = this;
  84378. var primitives = mesh.primitives;
  84379. if (!primitives || primitives.length === 0) {
  84380. throw new Error(context + ": Primitives are missing");
  84381. }
  84382. this._createMorphTargets(context, node, mesh);
  84383. this._loadAllVertexDataAsync(context, mesh, function () {
  84384. _this._loadMorphTargets(context, node, mesh);
  84385. var vertexData = new BABYLON.VertexData();
  84386. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84387. var primitive = primitives_1[_i];
  84388. vertexData.merge(primitive.vertexData);
  84389. }
  84390. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84391. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84392. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84393. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84394. node.babylonMesh.subMeshes = [];
  84395. var verticesStart = 0;
  84396. var indicesStart = 0;
  84397. for (var index = 0; index < primitives.length; index++) {
  84398. var vertexData_1 = primitives[index].vertexData;
  84399. var verticesCount = vertexData_1.positions.length;
  84400. var indicesCount = vertexData_1.indices.length;
  84401. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84402. verticesStart += verticesCount;
  84403. indicesStart += indicesCount;
  84404. }
  84405. ;
  84406. });
  84407. if (primitives.length === 1) {
  84408. var primitive = primitives[0];
  84409. if (primitive.material == null) {
  84410. node.babylonMesh.material = this._getDefaultMaterial();
  84411. }
  84412. else {
  84413. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84414. if (!material) {
  84415. throw new Error(context + ": Failed to find material " + primitive.material);
  84416. }
  84417. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84418. if (isNew) {
  84419. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84420. }
  84421. node.babylonMesh.material = babylonMaterial;
  84422. });
  84423. }
  84424. }
  84425. else {
  84426. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84427. node.babylonMesh.material = multiMaterial;
  84428. var subMaterials_1 = multiMaterial.subMaterials;
  84429. var _loop_1 = function (index) {
  84430. var primitive = primitives[index];
  84431. if (primitive.material == null) {
  84432. subMaterials_1[index] = this_1._getDefaultMaterial();
  84433. }
  84434. else {
  84435. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84436. if (!material) {
  84437. throw new Error(context + ": Failed to find material " + primitive.material);
  84438. }
  84439. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84440. if (isNew) {
  84441. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84442. }
  84443. subMaterials_1[index] = babylonMaterial;
  84444. });
  84445. }
  84446. };
  84447. var this_1 = this;
  84448. for (var index = 0; index < primitives.length; index++) {
  84449. _loop_1(index);
  84450. }
  84451. ;
  84452. }
  84453. };
  84454. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84455. var primitives = mesh.primitives;
  84456. var numRemainingPrimitives = primitives.length;
  84457. var _loop_2 = function (index) {
  84458. var primitive = primitives[index];
  84459. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84460. primitive.vertexData = vertexData;
  84461. if (--numRemainingPrimitives === 0) {
  84462. onSuccess();
  84463. }
  84464. });
  84465. };
  84466. var this_2 = this;
  84467. for (var index = 0; index < primitives.length; index++) {
  84468. _loop_2(index);
  84469. }
  84470. };
  84471. /**
  84472. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  84473. * @param {ArrayBufferView} data
  84474. * @param {IGLTFAccessor} accessor
  84475. */
  84476. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  84477. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  84478. return data;
  84479. }
  84480. var buffer = data;
  84481. var factor = 1;
  84482. switch (accessor.componentType) {
  84483. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84484. factor = 1 / 255;
  84485. break;
  84486. }
  84487. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84488. factor = 1 / 65535;
  84489. break;
  84490. }
  84491. default: {
  84492. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84493. }
  84494. }
  84495. var result = new Float32Array(accessor.count * 2);
  84496. for (var i = 0; i < result.length; ++i) {
  84497. result[i] = buffer[i] * factor;
  84498. }
  84499. return result;
  84500. };
  84501. /**
  84502. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  84503. * @param {ArrayBufferView} data
  84504. * @param {IGLTFAccessor} accessor
  84505. */
  84506. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  84507. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  84508. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  84509. return data;
  84510. }
  84511. var buffer = data;
  84512. var factor = 1;
  84513. switch (accessor.componentType) {
  84514. case GLTF2.EComponentType.FLOAT: {
  84515. factor = 1;
  84516. break;
  84517. }
  84518. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84519. factor = 1 / 255;
  84520. break;
  84521. }
  84522. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84523. factor = 1 / 65535;
  84524. break;
  84525. }
  84526. default: {
  84527. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84528. }
  84529. }
  84530. var result = new Float32Array(accessor.count * 4);
  84531. if (colorComponentCount === 4) {
  84532. for (var i = 0; i < result.length; ++i) {
  84533. result[i] = buffer[i] * factor;
  84534. }
  84535. }
  84536. else {
  84537. var offset = 0;
  84538. for (var i = 0; i < result.length; ++i) {
  84539. if ((i + 1) % 4 === 0) {
  84540. result[i] = 1;
  84541. }
  84542. else {
  84543. result[i] = buffer[offset++] * factor;
  84544. }
  84545. }
  84546. }
  84547. return result;
  84548. };
  84549. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  84550. var _this = this;
  84551. var attributes = primitive.attributes;
  84552. if (!attributes) {
  84553. throw new Error(context + ": Attributes are missing");
  84554. }
  84555. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  84556. // TODO: handle other primitive modes
  84557. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  84558. }
  84559. var vertexData = new BABYLON.VertexData();
  84560. var numRemainingAttributes = Object.keys(attributes).length;
  84561. var _loop_3 = function (attribute) {
  84562. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  84563. if (!accessor) {
  84564. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84565. }
  84566. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84567. switch (attribute) {
  84568. case "POSITION": {
  84569. vertexData.positions = data;
  84570. break;
  84571. }
  84572. case "NORMAL": {
  84573. vertexData.normals = data;
  84574. break;
  84575. }
  84576. case "TANGENT": {
  84577. vertexData.tangents = data;
  84578. break;
  84579. }
  84580. case "TEXCOORD_0": {
  84581. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84582. break;
  84583. }
  84584. case "TEXCOORD_1": {
  84585. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84586. break;
  84587. }
  84588. case "JOINTS_0": {
  84589. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  84590. break;
  84591. }
  84592. case "WEIGHTS_0": {
  84593. //TODO: need to add support for normalized weights.
  84594. vertexData.matricesWeights = data;
  84595. break;
  84596. }
  84597. case "COLOR_0": {
  84598. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  84599. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  84600. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  84601. mesh.hasVertexAlpha = hasVertexAlpha;
  84602. }
  84603. break;
  84604. }
  84605. default: {
  84606. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  84607. break;
  84608. }
  84609. }
  84610. if (--numRemainingAttributes === 0) {
  84611. if (primitive.indices == null) {
  84612. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  84613. for (var i = 0; i < vertexData.indices.length; i++) {
  84614. vertexData.indices[i] = i;
  84615. }
  84616. onSuccess(vertexData);
  84617. }
  84618. else {
  84619. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  84620. if (!indicesAccessor) {
  84621. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  84622. }
  84623. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  84624. vertexData.indices = data;
  84625. onSuccess(vertexData);
  84626. });
  84627. }
  84628. }
  84629. });
  84630. };
  84631. var this_3 = this;
  84632. for (var attribute in attributes) {
  84633. _loop_3(attribute);
  84634. }
  84635. };
  84636. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  84637. var primitives = mesh.primitives;
  84638. var targets = primitives[0].targets;
  84639. if (!targets) {
  84640. return;
  84641. }
  84642. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  84643. var primitive = primitives_2[_i];
  84644. if (!primitive.targets || primitive.targets.length != targets.length) {
  84645. throw new Error(context + ": All primitives are required to list the same number of targets");
  84646. }
  84647. }
  84648. var morphTargetManager = new BABYLON.MorphTargetManager();
  84649. node.babylonMesh.morphTargetManager = morphTargetManager;
  84650. for (var index = 0; index < targets.length; index++) {
  84651. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  84652. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  84653. }
  84654. };
  84655. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  84656. var morphTargetManager = node.babylonMesh.morphTargetManager;
  84657. if (!morphTargetManager) {
  84658. return;
  84659. }
  84660. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  84661. var numTargets = morphTargetManager.numTargets;
  84662. for (var index = 0; index < numTargets; index++) {
  84663. var vertexData = new BABYLON.VertexData();
  84664. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  84665. var primitive = _a[_i];
  84666. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  84667. }
  84668. if (!vertexData.positions) {
  84669. throw new Error(context + ": Positions are missing");
  84670. }
  84671. var target = morphTargetManager.getTarget(index);
  84672. target.setPositions(vertexData.positions);
  84673. target.setNormals(vertexData.normals);
  84674. target.setTangents(vertexData.tangents);
  84675. }
  84676. });
  84677. };
  84678. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  84679. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  84680. var _loop_4 = function (primitive) {
  84681. var targets = primitive.targets;
  84682. primitive.targetsVertexData = new Array(targets.length);
  84683. var _loop_5 = function (index) {
  84684. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  84685. primitive.targetsVertexData[index] = vertexData;
  84686. if (--numRemainingTargets === 0) {
  84687. onSuccess();
  84688. }
  84689. });
  84690. };
  84691. for (var index = 0; index < targets.length; index++) {
  84692. _loop_5(index);
  84693. }
  84694. };
  84695. var this_4 = this;
  84696. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  84697. var primitive = _a[_i];
  84698. _loop_4(primitive);
  84699. }
  84700. };
  84701. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  84702. var targetVertexData = new BABYLON.VertexData();
  84703. var numRemainingAttributes = Object.keys(attributes).length;
  84704. var _loop_6 = function (attribute) {
  84705. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  84706. if (!accessor) {
  84707. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84708. }
  84709. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84710. // glTF stores morph target information as deltas while babylon.js expects the final data.
  84711. // As a result we have to add the original data to the delta to calculate the final data.
  84712. var values = data;
  84713. switch (attribute) {
  84714. case "POSITION": {
  84715. for (var i = 0; i < values.length; i++) {
  84716. values[i] += vertexData.positions[i];
  84717. }
  84718. targetVertexData.positions = values;
  84719. break;
  84720. }
  84721. case "NORMAL": {
  84722. for (var i = 0; i < values.length; i++) {
  84723. values[i] += vertexData.normals[i];
  84724. }
  84725. targetVertexData.normals = values;
  84726. break;
  84727. }
  84728. case "TANGENT": {
  84729. // Tangent data for morph targets is stored as xyz delta.
  84730. // The vertexData.tangent is stored as xyzw.
  84731. // So we need to skip every fourth vertexData.tangent.
  84732. for (var i = 0, j = 0; i < values.length; i++, j++) {
  84733. values[i] += vertexData.tangents[j];
  84734. if ((i + 1) % 3 == 0) {
  84735. j++;
  84736. }
  84737. }
  84738. targetVertexData.tangents = values;
  84739. break;
  84740. }
  84741. default: {
  84742. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  84743. break;
  84744. }
  84745. }
  84746. if (--numRemainingAttributes === 0) {
  84747. onSuccess(targetVertexData);
  84748. }
  84749. });
  84750. };
  84751. var this_5 = this;
  84752. for (var attribute in attributes) {
  84753. _loop_6(attribute);
  84754. }
  84755. };
  84756. GLTFLoader.prototype._loadTransform = function (node) {
  84757. var position = BABYLON.Vector3.Zero();
  84758. var rotation = BABYLON.Quaternion.Identity();
  84759. var scaling = BABYLON.Vector3.One();
  84760. if (node.matrix) {
  84761. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  84762. matrix.decompose(scaling, rotation, position);
  84763. }
  84764. else {
  84765. if (node.translation)
  84766. position = BABYLON.Vector3.FromArray(node.translation);
  84767. if (node.rotation)
  84768. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  84769. if (node.scale)
  84770. scaling = BABYLON.Vector3.FromArray(node.scale);
  84771. }
  84772. node.babylonMesh.position = position;
  84773. node.babylonMesh.rotationQuaternion = rotation;
  84774. node.babylonMesh.scaling = scaling;
  84775. };
  84776. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  84777. var _this = this;
  84778. if (skin.babylonSkeleton) {
  84779. onSuccess();
  84780. return;
  84781. }
  84782. var skeletonId = "skeleton" + skin.index;
  84783. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  84784. if (skin.inverseBindMatrices == null) {
  84785. this._loadBones(context, skin, null);
  84786. onSuccess();
  84787. }
  84788. else {
  84789. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  84790. if (!accessor) {
  84791. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  84792. }
  84793. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84794. _this._loadBones(context, skin, data);
  84795. onSuccess();
  84796. });
  84797. }
  84798. };
  84799. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  84800. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  84801. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84802. node.babylonAnimationTargets.push(babylonBone);
  84803. return babylonBone;
  84804. };
  84805. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  84806. var babylonBones = {};
  84807. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  84808. var index = _a[_i];
  84809. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84810. if (!node) {
  84811. throw new Error(context + ": Failed to find joint " + index);
  84812. }
  84813. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  84814. }
  84815. };
  84816. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  84817. var babylonBone = babylonBones[node.index];
  84818. if (babylonBone) {
  84819. return babylonBone;
  84820. }
  84821. var boneIndex = skin.joints.indexOf(node.index);
  84822. var baseMatrix = BABYLON.Matrix.Identity();
  84823. if (inverseBindMatrixData && boneIndex !== -1) {
  84824. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  84825. baseMatrix.invertToRef(baseMatrix);
  84826. }
  84827. var babylonParentBone = null;
  84828. if (node.parent !== this._rootNode) {
  84829. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  84830. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  84831. }
  84832. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  84833. babylonBones[node.index] = babylonBone;
  84834. return babylonBone;
  84835. };
  84836. GLTFLoader.prototype._getNodeMatrix = function (node) {
  84837. return node.matrix ?
  84838. BABYLON.Matrix.FromArray(node.matrix) :
  84839. 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());
  84840. };
  84841. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  84842. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  84843. var index = indices_1[_i];
  84844. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84845. if (!node) {
  84846. throw new Error(context + ": Failed to find node " + index);
  84847. }
  84848. this._traverseNode(context, node, action, parentNode);
  84849. }
  84850. };
  84851. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  84852. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  84853. return;
  84854. }
  84855. if (!action(node, parentNode)) {
  84856. return;
  84857. }
  84858. if (node.children) {
  84859. this._traverseNodes(context, node.children, action, node);
  84860. }
  84861. };
  84862. GLTFLoader.prototype._loadAnimations = function () {
  84863. var animations = this._gltf.animations;
  84864. if (!animations) {
  84865. return;
  84866. }
  84867. for (var index = 0; index < animations.length; index++) {
  84868. var animation = animations[index];
  84869. this._loadAnimation("#/animations/" + index, animation);
  84870. }
  84871. };
  84872. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  84873. animation.targets = [];
  84874. for (var index = 0; index < animation.channels.length; index++) {
  84875. var channel = GLTFLoader._GetProperty(animation.channels, index);
  84876. if (!channel) {
  84877. throw new Error(context + ": Failed to find channel " + index);
  84878. }
  84879. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  84880. if (!sampler) {
  84881. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  84882. }
  84883. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  84884. }
  84885. };
  84886. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  84887. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  84888. if (!targetNode) {
  84889. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  84890. }
  84891. var targetPath;
  84892. var animationType;
  84893. switch (channel.target.path) {
  84894. case "translation": {
  84895. targetPath = "position";
  84896. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  84897. break;
  84898. }
  84899. case "rotation": {
  84900. targetPath = "rotationQuaternion";
  84901. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  84902. break;
  84903. }
  84904. case "scale": {
  84905. targetPath = "scaling";
  84906. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  84907. break;
  84908. }
  84909. case "weights": {
  84910. targetPath = "influence";
  84911. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  84912. break;
  84913. }
  84914. default: {
  84915. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  84916. }
  84917. }
  84918. var inputData;
  84919. var outputData;
  84920. var checkSuccess = function () {
  84921. if (!inputData || !outputData) {
  84922. return;
  84923. }
  84924. var outputBufferOffset = 0;
  84925. var getNextOutputValue;
  84926. switch (targetPath) {
  84927. case "position": {
  84928. getNextOutputValue = function () {
  84929. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  84930. outputBufferOffset += 3;
  84931. return value;
  84932. };
  84933. break;
  84934. }
  84935. case "rotationQuaternion": {
  84936. getNextOutputValue = function () {
  84937. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  84938. outputBufferOffset += 4;
  84939. return value;
  84940. };
  84941. break;
  84942. }
  84943. case "scaling": {
  84944. getNextOutputValue = function () {
  84945. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  84946. outputBufferOffset += 3;
  84947. return value;
  84948. };
  84949. break;
  84950. }
  84951. case "influence": {
  84952. getNextOutputValue = function () {
  84953. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  84954. var value = new Array(numTargets);
  84955. for (var i = 0; i < numTargets; i++) {
  84956. value[i] = outputData[outputBufferOffset++];
  84957. }
  84958. return value;
  84959. };
  84960. break;
  84961. }
  84962. }
  84963. sampler.interpolation = sampler.interpolation || "LINEAR";
  84964. var getNextKey;
  84965. switch (sampler.interpolation) {
  84966. case "STEP": {
  84967. getNextKey = function (frameIndex) { return ({
  84968. frame: inputData[frameIndex],
  84969. value: getNextOutputValue(),
  84970. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  84971. }); };
  84972. break;
  84973. }
  84974. case "LINEAR": {
  84975. getNextKey = function (frameIndex) { return ({
  84976. frame: inputData[frameIndex],
  84977. value: getNextOutputValue()
  84978. }); };
  84979. break;
  84980. }
  84981. case "CUBICSPLINE": {
  84982. getNextKey = function (frameIndex) { return ({
  84983. frame: inputData[frameIndex],
  84984. inTangent: getNextOutputValue(),
  84985. value: getNextOutputValue(),
  84986. outTangent: getNextOutputValue()
  84987. }); };
  84988. break;
  84989. }
  84990. default: {
  84991. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  84992. }
  84993. }
  84994. ;
  84995. var keys;
  84996. if (inputData.length === 1) {
  84997. var key = getNextKey(0);
  84998. keys = [
  84999. { frame: key.frame, value: key.value },
  85000. { frame: key.frame + 1, value: key.value }
  85001. ];
  85002. }
  85003. else {
  85004. keys = new Array(inputData.length);
  85005. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85006. keys[frameIndex] = getNextKey(frameIndex);
  85007. }
  85008. }
  85009. if (targetPath === "influence") {
  85010. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85011. var _loop_7 = function (targetIndex) {
  85012. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85013. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  85014. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85015. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85016. frame: key.frame,
  85017. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85018. value: key.value[targetIndex],
  85019. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85020. }); }));
  85021. morphTarget.animations.push(babylonAnimation);
  85022. animation.targets.push(morphTarget);
  85023. };
  85024. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85025. _loop_7(targetIndex);
  85026. }
  85027. }
  85028. else {
  85029. var animationName = animation.name || "anim" + animation.index;
  85030. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85031. babylonAnimation.setKeys(keys);
  85032. if (targetNode.babylonAnimationTargets) {
  85033. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85034. var target = _a[_i];
  85035. target.animations.push(babylonAnimation.clone());
  85036. animation.targets.push(target);
  85037. }
  85038. }
  85039. }
  85040. };
  85041. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85042. if (!inputAccessor) {
  85043. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85044. }
  85045. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85046. inputData = data;
  85047. checkSuccess();
  85048. });
  85049. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85050. if (!outputAccessor) {
  85051. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85052. }
  85053. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85054. outputData = data;
  85055. checkSuccess();
  85056. });
  85057. };
  85058. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85059. var _this = this;
  85060. this._addPendingData(buffer);
  85061. if (buffer.loadedData) {
  85062. onSuccess(buffer.loadedData);
  85063. this._removePendingData(buffer);
  85064. }
  85065. else if (buffer.loadedObservable) {
  85066. buffer.loadedObservable.add(function (buffer) {
  85067. onSuccess(buffer.loadedData);
  85068. _this._removePendingData(buffer);
  85069. });
  85070. }
  85071. else {
  85072. if (!buffer.uri) {
  85073. throw new Error(context + ": Uri is missing");
  85074. }
  85075. buffer.loadedObservable = new BABYLON.Observable();
  85076. buffer.loadedObservable.add(function (buffer) {
  85077. onSuccess(buffer.loadedData);
  85078. _this._removePendingData(buffer);
  85079. });
  85080. this._loadUriAsync(context, buffer.uri, function (data) {
  85081. buffer.loadedData = data;
  85082. buffer.loadedObservable.notifyObservers(buffer);
  85083. buffer.loadedObservable = undefined;
  85084. });
  85085. }
  85086. };
  85087. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85088. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85089. if (!buffer) {
  85090. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85091. }
  85092. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85093. var data;
  85094. try {
  85095. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85096. }
  85097. catch (e) {
  85098. throw new Error(context + ": " + e.message);
  85099. }
  85100. onSuccess(data);
  85101. });
  85102. };
  85103. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85104. var _this = this;
  85105. if (accessor.sparse) {
  85106. throw new Error(context + ": Sparse accessors are not currently supported");
  85107. }
  85108. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85109. if (!bufferView) {
  85110. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85111. }
  85112. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85113. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85114. var data;
  85115. var byteOffset = accessor.byteOffset || 0;
  85116. var byteStride = bufferView.byteStride;
  85117. if (byteStride === 0) {
  85118. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85119. }
  85120. try {
  85121. switch (accessor.componentType) {
  85122. case GLTF2.EComponentType.BYTE: {
  85123. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85124. break;
  85125. }
  85126. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85127. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85128. break;
  85129. }
  85130. case GLTF2.EComponentType.SHORT: {
  85131. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85132. break;
  85133. }
  85134. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85135. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85136. break;
  85137. }
  85138. case GLTF2.EComponentType.UNSIGNED_INT: {
  85139. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85140. break;
  85141. }
  85142. case GLTF2.EComponentType.FLOAT: {
  85143. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85144. break;
  85145. }
  85146. default: {
  85147. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85148. }
  85149. }
  85150. }
  85151. catch (e) {
  85152. throw new Error(context + ": " + e);
  85153. }
  85154. onSuccess(data);
  85155. });
  85156. };
  85157. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85158. byteOffset += data.byteOffset;
  85159. var targetLength = count * numComponents;
  85160. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85161. return new typedArray(data.buffer, byteOffset, targetLength);
  85162. }
  85163. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85164. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85165. var targetBuffer = new typedArray(targetLength);
  85166. var sourceIndex = 0;
  85167. var targetIndex = 0;
  85168. while (targetIndex < targetLength) {
  85169. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85170. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85171. targetIndex++;
  85172. }
  85173. sourceIndex += elementStride;
  85174. }
  85175. return targetBuffer;
  85176. };
  85177. GLTFLoader.prototype._addPendingData = function (data) {
  85178. if (!this._renderReady) {
  85179. this._renderPendingCount++;
  85180. }
  85181. this._addLoaderPendingData(data);
  85182. };
  85183. GLTFLoader.prototype._removePendingData = function (data) {
  85184. var _this = this;
  85185. if (!this._renderReady) {
  85186. if (--this._renderPendingCount === 0) {
  85187. this._addLoaderPendingData(this);
  85188. this._compileMaterialsAsync(function () {
  85189. _this._compileShadowGeneratorsAsync(function () {
  85190. _this._removeLoaderPendingData(_this);
  85191. _this._renderReady = true;
  85192. _this._onRenderReady();
  85193. });
  85194. });
  85195. }
  85196. }
  85197. this._removeLoaderPendingData(data);
  85198. };
  85199. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85200. this._loaderPendingCount++;
  85201. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85202. var tracker = _a[_i];
  85203. tracker._addPendingData(data);
  85204. }
  85205. };
  85206. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85207. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85208. var tracker = _a[_i];
  85209. tracker._removePendingData(data);
  85210. }
  85211. if (--this._loaderPendingCount === 0) {
  85212. this._onComplete();
  85213. }
  85214. };
  85215. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85216. var _this = this;
  85217. var tracker = new GLTFLoaderTracker(function () {
  85218. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85219. onComplete();
  85220. });
  85221. this._loaderTrackers.push(tracker);
  85222. this._addLoaderPendingData(tracker);
  85223. action();
  85224. this._removeLoaderPendingData(tracker);
  85225. };
  85226. GLTFLoader.prototype._getDefaultMaterial = function () {
  85227. if (!this._defaultMaterial) {
  85228. var id = "__gltf_default";
  85229. var material = this._babylonScene.getMaterialByName(id);
  85230. if (!material) {
  85231. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85232. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85233. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85234. material.metallic = 1;
  85235. material.roughness = 1;
  85236. }
  85237. this._defaultMaterial = material;
  85238. }
  85239. return this._defaultMaterial;
  85240. };
  85241. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85242. var babylonMaterial = material.babylonMaterial;
  85243. // Ensure metallic workflow
  85244. babylonMaterial.metallic = 1;
  85245. babylonMaterial.roughness = 1;
  85246. var properties = material.pbrMetallicRoughness;
  85247. if (!properties) {
  85248. return;
  85249. }
  85250. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85251. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85252. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85253. if (properties.baseColorTexture) {
  85254. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85255. if (!texture) {
  85256. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85257. }
  85258. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85259. }
  85260. if (properties.metallicRoughnessTexture) {
  85261. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85262. if (!texture) {
  85263. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85264. }
  85265. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85266. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85267. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85268. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85269. }
  85270. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85271. };
  85272. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85273. if (material.babylonMaterial) {
  85274. assign(material.babylonMaterial, false);
  85275. return;
  85276. }
  85277. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85278. return;
  85279. }
  85280. this._createPbrMaterial(material);
  85281. this._loadMaterialBaseProperties(context, material);
  85282. this._loadMaterialMetallicRoughnessProperties(context, material);
  85283. assign(material.babylonMaterial, true);
  85284. };
  85285. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85286. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85287. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85288. material.babylonMaterial = babylonMaterial;
  85289. };
  85290. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85291. var babylonMaterial = material.babylonMaterial;
  85292. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85293. if (material.doubleSided) {
  85294. babylonMaterial.backFaceCulling = false;
  85295. babylonMaterial.twoSidedLighting = true;
  85296. }
  85297. if (material.normalTexture) {
  85298. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85299. if (!texture) {
  85300. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85301. }
  85302. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85303. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85304. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85305. if (material.normalTexture.scale != null) {
  85306. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85307. }
  85308. }
  85309. if (material.occlusionTexture) {
  85310. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85311. if (!texture) {
  85312. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85313. }
  85314. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85315. babylonMaterial.useAmbientInGrayScale = true;
  85316. if (material.occlusionTexture.strength != null) {
  85317. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85318. }
  85319. }
  85320. if (material.emissiveTexture) {
  85321. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85322. if (!texture) {
  85323. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85324. }
  85325. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85326. }
  85327. };
  85328. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85329. var babylonMaterial = material.babylonMaterial;
  85330. var alphaMode = material.alphaMode || "OPAQUE";
  85331. switch (alphaMode) {
  85332. case "OPAQUE": {
  85333. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85334. break;
  85335. }
  85336. case "MASK": {
  85337. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85338. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85339. if (colorFactor) {
  85340. if (colorFactor[3] == 0) {
  85341. babylonMaterial.alphaCutOff = 1;
  85342. }
  85343. else {
  85344. babylonMaterial.alphaCutOff /= colorFactor[3];
  85345. }
  85346. }
  85347. if (babylonMaterial.albedoTexture) {
  85348. babylonMaterial.albedoTexture.hasAlpha = true;
  85349. }
  85350. break;
  85351. }
  85352. case "BLEND": {
  85353. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85354. if (colorFactor) {
  85355. babylonMaterial.alpha = colorFactor[3];
  85356. }
  85357. if (babylonMaterial.albedoTexture) {
  85358. babylonMaterial.albedoTexture.hasAlpha = true;
  85359. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85360. }
  85361. break;
  85362. }
  85363. default: {
  85364. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85365. }
  85366. }
  85367. };
  85368. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85369. var _this = this;
  85370. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85371. if (!sampler) {
  85372. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85373. }
  85374. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85375. this._addPendingData(texture);
  85376. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85377. _this._tryCatchOnError(function () {
  85378. _this._removePendingData(texture);
  85379. });
  85380. }, function (message) {
  85381. _this._tryCatchOnError(function () {
  85382. throw new Error(context + ": " + message);
  85383. });
  85384. });
  85385. if (texture.url) {
  85386. babylonTexture.updateURL(texture.url);
  85387. }
  85388. else if (texture.dataReadyObservable) {
  85389. texture.dataReadyObservable.add(function (texture) {
  85390. babylonTexture.updateURL(texture.url);
  85391. });
  85392. }
  85393. else {
  85394. texture.dataReadyObservable = new BABYLON.Observable();
  85395. texture.dataReadyObservable.add(function (texture) {
  85396. babylonTexture.updateURL(texture.url);
  85397. });
  85398. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85399. if (!image_1) {
  85400. throw new Error(context + ": Failed to find source " + texture.source);
  85401. }
  85402. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85403. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85404. texture.dataReadyObservable.notifyObservers(texture);
  85405. texture.dataReadyObservable = undefined;
  85406. });
  85407. }
  85408. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85409. babylonTexture.wrapU = sampler.wrapU;
  85410. babylonTexture.wrapV = sampler.wrapV;
  85411. babylonTexture.name = texture.name || "texture" + texture.index;
  85412. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85413. return babylonTexture;
  85414. };
  85415. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85416. if (sampler.noMipMaps != undefined) {
  85417. return;
  85418. }
  85419. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85420. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85421. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85422. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85423. };
  85424. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85425. if (image.uri) {
  85426. this._loadUriAsync(context, image.uri, onSuccess);
  85427. }
  85428. else {
  85429. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85430. if (!bufferView) {
  85431. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85432. }
  85433. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85434. }
  85435. };
  85436. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85437. var _this = this;
  85438. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85439. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85440. return;
  85441. }
  85442. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85443. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85444. }
  85445. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85446. _this._tryCatchOnError(function () {
  85447. onSuccess(new Uint8Array(data));
  85448. });
  85449. }, function (event) {
  85450. _this._tryCatchOnError(function () {
  85451. if (request && !_this._renderReady) {
  85452. request._lengthComputable = event.lengthComputable;
  85453. request._loaded = event.loaded;
  85454. request._total = event.total;
  85455. _this._onProgress();
  85456. }
  85457. });
  85458. }, this._babylonScene.database, true, function (request, exception) {
  85459. _this._tryCatchOnError(function () {
  85460. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85461. });
  85462. });
  85463. this._requests.push(request);
  85464. request.onCompleteObservable.add(function () {
  85465. _this._requests.splice(_this._requests.indexOf(request), 1);
  85466. });
  85467. };
  85468. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  85469. if (this._disposed) {
  85470. return;
  85471. }
  85472. try {
  85473. handler();
  85474. }
  85475. catch (e) {
  85476. BABYLON.Tools.Error("glTF Loader: " + e.message);
  85477. if (this._errorCallback) {
  85478. this._errorCallback(e.message, e);
  85479. }
  85480. this.dispose();
  85481. }
  85482. };
  85483. GLTFLoader._AssignIndices = function (array) {
  85484. if (array) {
  85485. for (var index = 0; index < array.length; index++) {
  85486. array[index].index = index;
  85487. }
  85488. }
  85489. };
  85490. GLTFLoader._GetProperty = function (array, index) {
  85491. if (!array || index == undefined || !array[index]) {
  85492. return null;
  85493. }
  85494. return array[index];
  85495. };
  85496. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  85497. // Set defaults if undefined
  85498. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  85499. switch (mode) {
  85500. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85501. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85502. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85503. default:
  85504. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  85505. return BABYLON.Texture.WRAP_ADDRESSMODE;
  85506. }
  85507. };
  85508. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  85509. // Set defaults if undefined
  85510. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  85511. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  85512. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  85513. switch (minFilter) {
  85514. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  85515. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  85516. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  85517. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  85518. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  85519. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85520. default:
  85521. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85522. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85523. }
  85524. }
  85525. else {
  85526. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  85527. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  85528. }
  85529. switch (minFilter) {
  85530. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  85531. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  85532. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85533. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  85534. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  85535. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  85536. default:
  85537. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85538. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85539. }
  85540. }
  85541. };
  85542. GLTFLoader._GetNumComponents = function (context, type) {
  85543. switch (type) {
  85544. case "SCALAR": return 1;
  85545. case "VEC2": return 2;
  85546. case "VEC3": return 3;
  85547. case "VEC4": return 4;
  85548. case "MAT2": return 4;
  85549. case "MAT3": return 9;
  85550. case "MAT4": return 16;
  85551. }
  85552. throw new Error(context + ": Invalid type " + type);
  85553. };
  85554. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  85555. var _this = this;
  85556. if (this.useClipPlane) {
  85557. babylonMaterial.forceCompilation(babylonMesh, function () {
  85558. babylonMaterial.forceCompilation(babylonMesh, function () {
  85559. _this._tryCatchOnError(onSuccess);
  85560. }, { clipPlane: true });
  85561. });
  85562. }
  85563. else {
  85564. babylonMaterial.forceCompilation(babylonMesh, function () {
  85565. _this._tryCatchOnError(onSuccess);
  85566. });
  85567. }
  85568. };
  85569. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  85570. if (!this.compileMaterials || !this._gltf.materials) {
  85571. onSuccess();
  85572. return;
  85573. }
  85574. var meshes = this._getMeshes();
  85575. var remaining = 0;
  85576. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  85577. var mesh = meshes_1[_i];
  85578. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85579. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  85580. var subMaterial = _b[_a];
  85581. if (subMaterial) {
  85582. remaining++;
  85583. }
  85584. }
  85585. }
  85586. else if (mesh.material) {
  85587. remaining++;
  85588. }
  85589. }
  85590. if (remaining === 0) {
  85591. onSuccess();
  85592. return;
  85593. }
  85594. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  85595. var mesh = meshes_2[_c];
  85596. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85597. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  85598. var subMaterial = _e[_d];
  85599. if (subMaterial) {
  85600. this._compileMaterialAsync(subMaterial, mesh, function () {
  85601. if (--remaining === 0) {
  85602. onSuccess();
  85603. }
  85604. });
  85605. }
  85606. }
  85607. }
  85608. else if (mesh.material) {
  85609. this._compileMaterialAsync(mesh.material, mesh, function () {
  85610. if (--remaining === 0) {
  85611. onSuccess();
  85612. }
  85613. });
  85614. }
  85615. }
  85616. };
  85617. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  85618. var _this = this;
  85619. if (!this.compileShadowGenerators) {
  85620. onSuccess();
  85621. return;
  85622. }
  85623. var lights = this._babylonScene.lights;
  85624. var remaining = 0;
  85625. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  85626. var light = lights_1[_i];
  85627. var generator = light.getShadowGenerator();
  85628. if (generator) {
  85629. remaining++;
  85630. }
  85631. }
  85632. if (remaining === 0) {
  85633. onSuccess();
  85634. return;
  85635. }
  85636. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  85637. var light = lights_2[_a];
  85638. var generator = light.getShadowGenerator();
  85639. if (generator) {
  85640. generator.forceCompilation(function () {
  85641. if (--remaining === 0) {
  85642. _this._tryCatchOnError(onSuccess);
  85643. }
  85644. });
  85645. }
  85646. }
  85647. };
  85648. GLTFLoader.prototype._abortRequests = function () {
  85649. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  85650. var request = _a[_i];
  85651. request.abort();
  85652. }
  85653. this._requests.length = 0;
  85654. };
  85655. GLTFLoader.prototype._releaseResources = function () {
  85656. if (this._gltf.textures) {
  85657. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  85658. var texture = _a[_i];
  85659. if (texture.url) {
  85660. URL.revokeObjectURL(texture.url);
  85661. texture.url = undefined;
  85662. }
  85663. }
  85664. }
  85665. };
  85666. GLTFLoader.Extensions = {};
  85667. return GLTFLoader;
  85668. }());
  85669. GLTF2.GLTFLoader = GLTFLoader;
  85670. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  85671. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85672. })(BABYLON || (BABYLON = {}));
  85673. //# sourceMappingURL=babylon.glTFLoader.js.map
  85674. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85675. var BABYLON;
  85676. (function (BABYLON) {
  85677. var GLTF2;
  85678. (function (GLTF2) {
  85679. /**
  85680. * Utils functions for GLTF
  85681. */
  85682. var GLTFUtils = /** @class */ (function () {
  85683. function GLTFUtils() {
  85684. }
  85685. /**
  85686. * If the uri is a base64 string
  85687. * @param uri: the uri to test
  85688. */
  85689. GLTFUtils.IsBase64 = function (uri) {
  85690. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  85691. };
  85692. /**
  85693. * Decode the base64 uri
  85694. * @param uri: the uri to decode
  85695. */
  85696. GLTFUtils.DecodeBase64 = function (uri) {
  85697. var decodedString = atob(uri.split(",")[1]);
  85698. var bufferLength = decodedString.length;
  85699. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  85700. for (var i = 0; i < bufferLength; i++) {
  85701. bufferView[i] = decodedString.charCodeAt(i);
  85702. }
  85703. return bufferView.buffer;
  85704. };
  85705. GLTFUtils.ValidateUri = function (uri) {
  85706. return (uri.indexOf("..") === -1);
  85707. };
  85708. return GLTFUtils;
  85709. }());
  85710. GLTF2.GLTFUtils = GLTFUtils;
  85711. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85712. })(BABYLON || (BABYLON = {}));
  85713. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  85714. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85715. var BABYLON;
  85716. (function (BABYLON) {
  85717. var GLTF2;
  85718. (function (GLTF2) {
  85719. var GLTFLoaderExtension = /** @class */ (function () {
  85720. function GLTFLoaderExtension() {
  85721. this.enabled = true;
  85722. }
  85723. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  85724. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  85725. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  85726. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  85727. var _this = this;
  85728. if (!property.extensions) {
  85729. return false;
  85730. }
  85731. var extension = property.extensions[this.name];
  85732. if (!extension) {
  85733. return false;
  85734. }
  85735. // Clear out the extension before executing the action to avoid recursing into the same property.
  85736. property.extensions[this.name] = undefined;
  85737. action(context + "extensions/" + this.name, extension, function () {
  85738. // Restore the extension after completing the action.
  85739. property.extensions[_this.name] = extension;
  85740. });
  85741. return true;
  85742. };
  85743. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  85744. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  85745. };
  85746. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  85747. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  85748. };
  85749. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  85750. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  85751. };
  85752. GLTFLoaderExtension._ApplyExtensions = function (action) {
  85753. var extensions = GLTFLoaderExtension._Extensions;
  85754. if (!extensions) {
  85755. return false;
  85756. }
  85757. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  85758. var extension = extensions_1[_i];
  85759. if (extension.enabled && action(extension)) {
  85760. return true;
  85761. }
  85762. }
  85763. return false;
  85764. };
  85765. //
  85766. // Utilities
  85767. //
  85768. GLTFLoaderExtension._Extensions = [];
  85769. return GLTFLoaderExtension;
  85770. }());
  85771. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  85772. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85773. })(BABYLON || (BABYLON = {}));
  85774. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  85775. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  85776. var BABYLON;
  85777. (function (BABYLON) {
  85778. var GLTF2;
  85779. (function (GLTF2) {
  85780. var Extensions;
  85781. (function (Extensions) {
  85782. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  85783. var MSFTLOD = /** @class */ (function (_super) {
  85784. __extends(MSFTLOD, _super);
  85785. function MSFTLOD() {
  85786. var _this = _super !== null && _super.apply(this, arguments) || this;
  85787. /**
  85788. * Specify the minimal delay between LODs in ms (default = 250)
  85789. */
  85790. _this.Delay = 250;
  85791. return _this;
  85792. }
  85793. Object.defineProperty(MSFTLOD.prototype, "name", {
  85794. get: function () {
  85795. return "MSFT_lod";
  85796. },
  85797. enumerable: true,
  85798. configurable: true
  85799. });
  85800. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  85801. return this._loadExtension(context, node, function (context, extension, onComplete) {
  85802. for (var i = extension.ids.length - 1; i >= 0; i--) {
  85803. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  85804. if (!lodNode) {
  85805. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  85806. }
  85807. loader._traverseNode(context, lodNode, action, parentNode);
  85808. }
  85809. loader._traverseNode(context, node, action, parentNode);
  85810. onComplete();
  85811. });
  85812. };
  85813. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  85814. var _this = this;
  85815. return this._loadExtension(context, node, function (context, extension, onComplete) {
  85816. var nodes = [node];
  85817. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  85818. var index = _a[_i];
  85819. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  85820. if (!lodNode) {
  85821. throw new Error(context + ": Failed to find node " + index);
  85822. }
  85823. nodes.push(lodNode);
  85824. }
  85825. loader._addLoaderPendingData(node);
  85826. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  85827. loader._removeLoaderPendingData(node);
  85828. onComplete();
  85829. });
  85830. });
  85831. };
  85832. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  85833. var _this = this;
  85834. loader._whenAction(function () {
  85835. loader._loadNode(context, nodes[index]);
  85836. }, function () {
  85837. if (index !== nodes.length - 1) {
  85838. var previousNode = nodes[index + 1];
  85839. previousNode.babylonMesh.setEnabled(false);
  85840. }
  85841. if (index === 0) {
  85842. onComplete();
  85843. return;
  85844. }
  85845. setTimeout(function () {
  85846. loader._tryCatchOnError(function () {
  85847. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  85848. });
  85849. }, _this.Delay);
  85850. });
  85851. };
  85852. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  85853. var _this = this;
  85854. return this._loadExtension(context, material, function (context, extension, onComplete) {
  85855. var materials = [material];
  85856. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  85857. var index = _a[_i];
  85858. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  85859. if (!lodMaterial) {
  85860. throw new Error(context + ": Failed to find material " + index);
  85861. }
  85862. materials.push(lodMaterial);
  85863. }
  85864. loader._addLoaderPendingData(material);
  85865. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  85866. loader._removeLoaderPendingData(material);
  85867. onComplete();
  85868. });
  85869. });
  85870. };
  85871. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  85872. var _this = this;
  85873. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  85874. if (index === materials.length - 1) {
  85875. assign(babylonMaterial, isNew);
  85876. // Load the next LOD when the loader is ready to render.
  85877. loader._executeWhenRenderReady(function () {
  85878. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  85879. });
  85880. }
  85881. else {
  85882. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  85883. assign(babylonMaterial, isNew);
  85884. if (index === 0) {
  85885. onComplete();
  85886. }
  85887. else {
  85888. setTimeout(function () {
  85889. loader._tryCatchOnError(function () {
  85890. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  85891. });
  85892. }, _this.Delay);
  85893. }
  85894. });
  85895. }
  85896. });
  85897. };
  85898. return MSFTLOD;
  85899. }(GLTF2.GLTFLoaderExtension));
  85900. Extensions.MSFTLOD = MSFTLOD;
  85901. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  85902. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  85903. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85904. })(BABYLON || (BABYLON = {}));
  85905. //# sourceMappingURL=MSFT_lod.js.map
  85906. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  85907. var BABYLON;
  85908. (function (BABYLON) {
  85909. var GLTF2;
  85910. (function (GLTF2) {
  85911. var Extensions;
  85912. (function (Extensions) {
  85913. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  85914. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  85915. function KHRMaterialsPbrSpecularGlossiness() {
  85916. return _super !== null && _super.apply(this, arguments) || this;
  85917. }
  85918. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  85919. get: function () {
  85920. return "KHR_materials_pbrSpecularGlossiness";
  85921. },
  85922. enumerable: true,
  85923. configurable: true
  85924. });
  85925. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  85926. var _this = this;
  85927. return this._loadExtension(context, material, function (context, extension, onComplete) {
  85928. loader._createPbrMaterial(material);
  85929. loader._loadMaterialBaseProperties(context, material);
  85930. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  85931. assign(material.babylonMaterial, true);
  85932. onComplete();
  85933. });
  85934. };
  85935. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  85936. var babylonMaterial = material.babylonMaterial;
  85937. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  85938. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  85939. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  85940. if (properties.diffuseTexture) {
  85941. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  85942. if (!texture) {
  85943. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  85944. }
  85945. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  85946. }
  85947. if (properties.specularGlossinessTexture) {
  85948. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  85949. if (!texture) {
  85950. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  85951. }
  85952. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  85953. babylonMaterial.reflectivityTexture.hasAlpha = true;
  85954. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  85955. }
  85956. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  85957. };
  85958. return KHRMaterialsPbrSpecularGlossiness;
  85959. }(GLTF2.GLTFLoaderExtension));
  85960. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  85961. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  85962. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  85963. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85964. })(BABYLON || (BABYLON = {}));
  85965. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  85966. (function universalModuleDefinition(root, factory) {
  85967. var f = factory();
  85968. if (root && root["BABYLON"]) {
  85969. return;
  85970. }
  85971. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  85972. globalObject["BABYLON"] = f;
  85973. if(typeof exports === 'object' && typeof module === 'object')
  85974. module.exports = f;
  85975. else if(typeof define === 'function' && define.amd)
  85976. define(["BABYLON"], factory);
  85977. else if(typeof exports === 'object')
  85978. exports["BABYLON"] = f;
  85979. else {
  85980. root["BABYLON"] = f;
  85981. }
  85982. })(this, function() {
  85983. return BABYLON;
  85984. });